Pages

Tuesday, September 27, 2011

Read response from HTTPpost method using HttpResponse (or any InputStream) as a String


This piece of code reads all inputstream response into string. Inputstream means of reading data from a source in a byte-wise manner.

 You get the entity response an InputStream object from HttpPost execute method. Essentially StringBuilder is a lot faster, and can be converted a normal string with .toString() method.

For reading the content of HttpResponse use convertStreamToString(response.getEntity().getContent())

HttpResponse responseGet = httpclient.execute(httppost);
HttpEntity entity = responseGet.getEntity();
if (entity != null) {
InputStream inputStreamResponse = entity.getContent();
result = convertStreamToString(inputStreamResponse);
}else {
 // code here for a response othet than 200.  A response 200 means the webpage was ok
 // Other codes include 404 - not found, 301 - redirect etc...
 // Display the response line.
System.out.println("Unable to load page - " + responseGet.getStatusLine());
}



ConvertStreamToString Method:
// Fast Implementation
private StringBuilder convertStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
   
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    // Read response until the end
    while ((line = rd.readLine()) != null) {
        total.append(line);
    }
   
    // Return full string
    return total;
}

// Slow Implementation
private String convertStreamToString(InputStream is) {
    String s = "";
    String line = "";
   
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
   
    // Read response until the end
    while ((line = rd.readLine()) != null) { s += line; }
   
    // Return full string
    return s;
}

No comments:

Post a Comment