HttpResponse entity to String

In previous post I explained how to post XML file to certain page on Web Server.
Response from Server can be read from HttpResponse entity, calling response.getEntity(), but it returns only coded message.
So, how then to get String value from it?

I found an answer on this blog Think Android.

You can use this function for getting HttpResponse entity in normal view.

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();
    }

1 Comment

You must be logged in to post a comment.