Android: Use HttpURLConnection instead of deprecated Apache module: HttpClient/HttpResponse

on

As Android deprecated Apache module like HttpClient, HttpResponse, we can use HttpURLConnection.

Here is some code sample:

try {
	URL url = new URL(onlineUrl);//use a proper url instead of onlineUrl
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setRequestProperty("User-Agent", "");
	connection.setRequestMethod("GET");//we can use POST instead of GET method also.
	connection.setDoInput(true);
	connection.connect();
	InputStream inputStream = connection.getInputStream();
	if (inputStream != null) {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		String line = "";
		StringBuilder result = new StringBuilder();
	while ((line = bufferedReader.readLine()) != null){
		result.append(line);
	}		
	inputStream.close();
	Log.i(TAG, "The result: " + result.toString());
	//return this result
	}
} catch (Exception e) {
	e.printStackTrace();
	Log.e(TAG, "Connection Error !!! - " + e.toString());
}

Leave a Reply

Your email address will not be published. Required fields are marked *