Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In httpclient what is the most elegant/correct way to turn HttpEntity to a String?

I'm fetching a web page using the Apache httpcomponents Java library. After connecting the result I get is an HttpEntity which has a method getContent() which returns an InputStream and also has a method writeTo() which writes to an OutputStream.

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

Some possible solutions:

  • Write to a ByteArrayOutputStream and then convert those bytes to a String with a String constructor
  • use InputStreamReader to read straight from the stream, and put into a StringBuilder

Both of these feel a bit ugly. Would you recommend choosing one of these or something else?

like image 541
Nick Fortescue Avatar asked Jan 11 '10 17:01

Nick Fortescue


People also ask

How do you read HttpEntity data?

To read the content from the entity, you can either retrieve the input stream via the HttpEntity. getContent() method, which returns an InputStream, or you can supply an output stream to the HttpEntity. writeTo(OutputStream) method, which will return once all content has been written to the given stream.

How do you read HttpEntity response?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

How do I find HttpEntity?

The HttpEntity can be obtained from the HttpResponse object. From the ContentType object we can get the mime-type by calling the getMimeType() method. This method will return a string value. To get the charset we can call the getCharset() method which will return a java.

What does EntityUtils toString do?

toString. Gets the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "ISO-8859-1" is used. defaultCharset - character set to be applied if none found in the entity, or if the entity provided charset is invalid or not available.


2 Answers

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

like image 76
Narasimha Reddy Lomadi Avatar answered Nov 15 '22 06:11

Narasimha Reddy Lomadi


What about (pseudo):

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

You would have to handle exceptions on your own in this case.

like image 31
Nate Avatar answered Nov 15 '22 06:11

Nate