Tuesday, 6 December 2011

Android - Get body of HTTP Response as String


Making HTTP requests in Android often results in the same type of boiler plate code being produced. One in particular that annoys me is having to get the response body as in InputStream and using BufferedReader and the likes.


Bundled along with Android is the org.apache.http libraries, which provide classes for easy interaction for common HTTP-related activities.


The following snippet shows how to perform an HTTP GET on a URI, and turn the response body into a string. In my case, I take the string and turn into a JSON object, but you might parse as XML or whatever.


DefaultHttpClient http = new DefaultHttpClient();
HttpGet httpMethod = new HttpGet();
httpMethod.setURI(new URI(SERVER_URI_GOES_HERE));
HttpResponse response = http.execute(httpMethod);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode)
{
    case 200:
        HttpEntity entity = response.getEntity();
if(entity != null)
{
String responseBody = EntityUtils.toString(entity);
                 
        }
        break;