Saturday, February 11, 2012

How to Get the content from a HttpResponse (or any InputStream) as a String in android?


This snippet reads all of the InputStream into a String. Useful for any kind of InputStream, including the content of aHttpResponse after a HttpClient request. See also this answer on SO. Essentially StringBuilder is a lot faster, and can be converted to a normal String with the .toString() method.
For reading the content of a HttpResponse use inputStreamToString(response.getEntity().getContent()).
// Fast Implementation
private StringBuilder inputStreamToString(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 inputStreamToString(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