Wednesday, December 30, 2009

Getting Response Body of HttpResponse

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) { e.printStackTrace(); } catch (IOException e) { if (entity != null) { try { entity.consumeContent(); } 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) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); StringBuilder buffer = new StringBuilder(); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } finally { reader.close(); } 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

[Via http://thinkandroid.wordpress.com]

No comments:

Post a Comment