Skip to content

Getting Response Body of HttpResponse

December 30, 2009

Hey everyone,

For those of you who want to do stuff with web POST and GET methods and need some help getting the response body of your HttpResponse objects, this post is for you!

public static String getResponseBody(HttpResponse response) {

String response_text = null;

HttpEntity entity = null;

try {

entity = response.getEntity();

response_text = _getResponseBody(entity);

} catch (ParseException e) {


} catch (IOException e) {

if (entity != null) {

try {


} catch (IOException e1) {




return response_text;


public static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {

if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }

InputStream instream = entity.getContent();

if (instream == null) { return ""; }

if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException(

"HTTP entity too large to be buffered in memory"); }

String charset = getContentCharSet(entity);

if (charset == null) {



Reader reader = new InputStreamReader(instream, charset);

StringBuilder buffer = new StringBuilder();

try {

char[] tmp = new char[1024];

int l;

while ((l = != -1) {

buffer.append(tmp, 0, l);


} finally {



return buffer.toString();


public String getContentCharSet(final HttpEntity entity) throws ParseException {

if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }

String charset = null;

if (entity.getContentType() != null) {

HeaderElement values[] = entity.getContentType().getElements();

if (values.length > 0) {

NameValuePair param = values[0].getParameterByName("charset");

if (param != null) {

charset = param.getValue();




return charset;


Basically, all this is just complicated code for getting the CharSet of your HttpResponse entity, and then creating a buffer that slowly makes the response string one char at a time. Besides that everything else seems self explanatory, but let me know if you have questions and I’ll do my best to answer them.

Happy coding.

– jwei

21 Comments leave one →
  1. vixper permalink
    January 5, 2010 6:14 am

    Hi, i’m trying to login to (it’s https).
    I’m trying to use your example, but I’m unable to understand how it works and how to use it…can you please help me?

  2. January 13, 2010 1:26 am

    Hi mate,

    Thanks, the way to convert an entity to an inputstream was exactly what i was looking for.

    Thanks for the time saving πŸ™‚

  3. another_sam permalink
    June 20, 2010 6:20 am

    i can not believe this. how is it possible that android being a fresh framework does not provide this.

    you are coding at the top of a stack with a pretended high-level language and a new and shiny framework, and you need 50 extra lines of code plenty of classes I never heard of to get the body of an HTTP response. in 2010. i can not believe this.

    now talking to jwei512, thank you indeed. it would took me months to figure out how to do this by myself.

    • June 20, 2010 4:32 pm

      haha no problem

      and yea dealing with web / server stuff in java tends to be pretty messy in general – kind of sucks

      – jwei

  4. Viren permalink
    September 6, 2010 6:39 am

    Thanks. This is what I was looking for.

  5. Renny permalink
    October 27, 2010 6:24 am

    Thank you for this sample!

  6. ichirohang permalink
    January 4, 2011 4:44 am

    It’s really nice article, However i encounter problem. I couldn’t get all data from server. My return data are in xml format, i check return data, it has empty space afert \n\r. I don’t understand why i couldn’t get all the data from the server.

    Thank you

    • January 5, 2011 1:47 pm

      Check that you are formatting the data correctly when you return it from your server.

      In other words, try hitting the GET URL manually (just in your browser) and make sure that the data returned is actually given in an XML form. Otherwise, in some browsers (i.e. Firefox) it’ll throw you a warning telling you that your XML is improperly formatted and that should hint you as to what might be going wrong. This has happened to me many many times when I work with JAVA servlets and such.

      – jwei

  7. mrqzzz permalink
    January 7, 2011 2:48 am

    Thank you… never would immagine it was so complicated ..!!!!

  8. Colm Shannon permalink
    February 24, 2011 6:04 am

    I’m having a problem with this line:

    Getting the following error after I’ve imported everything:
    The method _getResponseBody(HttpEntity) is undefined for the type TestClass

    Any suggestions?

  9. Colm Shannon permalink
    February 24, 2011 6:04 am

    I’m an idiot… never mind πŸ™‚

  10. March 3, 2011 3:23 pm

    I used to use this code but changed to something simpler which supported server errors.

    It’s easier to pass a “BasicResponseHandler” to “HttpClient.execute(httppost, new BasicResponseHandler())” so you get the string AND receive exceptions when the server hits a 404 or 500.

    See my post for more info.

  11. Colm Shannon permalink
    March 10, 2011 7:54 am

    This code seems to have the same problem I was having, where it only reads in the first 35~ lines of the entity response. Has this something to do with buffer over flow?

  12. ashok permalink
    July 6, 2011 8:43 pm

    I am getting IOException when reading larget data..i used read( buffer , 0 , 20480) ..any suggestions ?

  13. July 20, 2011 10:59 am

    Why would you use this rather than just something like the following? (surrounded with a try/catch). Not asking in a hostile way, just interested.

    URL url = new URL("http://www..........php?"+query);
    URLConnection conn = url.openConnection();
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String mString = rd.readLine();
    • November 2, 2011 10:34 am

      Hey Mat,

      I’ve just found that mine is a little more robust and also allows you to specify character encoding types, etc.

      However if your method works for you then by all means use it! Definitely less verbose.

      – jwei

  14. August 2, 2011 9:16 pm

    Thank you! This code did exactly what I needed and you saved me a lot of time by posting this. Now on to figuring out why my PHP keeps mangling my UTF-8 strings…

  15. Mr Tnks permalink
    September 26, 2011 2:17 pm

    thank you!

  16. hello world permalink
    September 10, 2012 5:35 am

    I have just tested this and it turns out that I got the same results as when using this one line of code: result = EntityUtils.toString(response.getEntity());


  1. HttpResponse entity to String – Moishe Beshkin

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: