Q: Make an HTTP request with android

Test Case #15


File ID: #3506039-2-cc


   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?: