Q: Make an HTTP request with android

D: I have searched everywhere but I couldn't find my answer, is there a way to make an simple HTTP request? I want to request an PHP page / script on one of my website but I don't want to show the webpage.
If possible I even want to do it in the background (in an BroadcastReceiver).

Test Case #14


File ID: #3506039-1-cc


String responseString ="";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(baseURL +"?user=" +user +"&lat=" +lat +"&lon=" +lon));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() = = HttpStatus.SC_OK) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.getEntity().writeTo(out);
    out.close();
    responseString = out.toString();
// ..more logic
} else {
// Closes the connection.
    response.getEntity().getContent().close();
    throw new IOException(statusLine.getReasonPhrase());
}



class RequestTask extends AsyncTask{
@Override
protected String doInBackground(FixitRequest... fixitRequests) {
Log.d(Constants.TAG, "Entering RequestTask");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(fixitRequests[0].getUrl()));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
// TODO: Save the picture on the server.
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d(Constants.TAG, "Exiting RequestTask");
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}


  1. For gingerbread or greater its actually advised to use HttpURLConnection over the apache library, see http://android-developers.blogspot.com/2011/09/androids-http-clients.html . Its less taxing on the battery and has better performance
  2. As of Honeycomb (SDK 11) the asynchronous approach is the way to go. A [NetworkOnMainThreadException](http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html) gets thrown when you try to run an HTTP request from the main thread.
  3. ResponseString = out.toString() needs to be before the out.close() call. Actually, you should probably have the out.close() in a finally block. But overall, very helpful answer (+1), thanks!

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: