In httpclient, the most elegant / proper way to turn HttpEntity into a String?

I am retrieving a webpage using Apache httpcomponents Java library . After connecting the result, I get HttpEntityone that has a method getContent()that returns InputStream, and also has a method writeTo()that writes to OutputStream.

I want to turn the result into a String to extract the information. What is the most elegant (and safest) way to do this?

Some possible solutions:

  • Write to ByteArrayOutputStreamand then convert these bytes to String with a string constructor
  • use InputStreamReader to read directly from the stream and put in StringBuilder

Both of them feel a little ugly. Would you recommend choosing one of them or something else?

+5
source share
3 answers

How about (pseudo):

BasicResponseHandler handler = new org.apache.http.impl.client.BasicResponseHandler ();    
String str = httpClient.execute(request, handler);

In this case, you have to handle the exceptions yourself.

+4
source

System.out.println (EntityUtils.toString (httpResponse.getEntity ()));

+6
source

, , . IOUtils.toString() Commons-IO, .

0

All Articles