Android: Extract a HTTP web page content into a String

Initially I found a lot of code samples on the web explaining how to read from the IO stream of the HttpEntity. I followed that, but found the code to be fairly bloated and slow.

After some time, I found that the code sample was unable to cope with HTTP status codes such as 404 or server error 500.

Then I found a much easier way of doing it. Instead of adding 54 lines of code to go through the trouble of parsing HttpEntity, reading the stream out into a buffer and String, we just let the Android API handle it.

Original method:

HttpClient httpclient = getHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response;

// Add post data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
response = httpclient.execute(httppost);

Xml.parse(getResponseBody(response), new CustomXmlParser());

New method:

HttpClient httpclient = getHttpClient();
HttpPost httppost = new HttpPost(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String xml;

// Add post data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
xml = httpclient.execute(httppost, responseHandler);

Xml.parse(xml, new CustomXmlParser());

As you can see, theres not much of a chance in the actual code except for the HttpClient.execute() call where the extra responseHandler is given.

The call to execute() will parse the data straight to a String for us, so no need to get into the nitty gritty anymore!

It'll also throw exceptions when the server runs into any errors such as 404 or server error 500.

A bonus is that you'll get to cull about 50+ lines of code from your project.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog