Nick Fortescue
Nick Fortescue

Reputation: 44173

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:

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

Upvotes: 5

Views: 2736

Answers (3)

Narasimha Reddy Lomadi
Narasimha Reddy Lomadi

Reputation: 139

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

Upvotes: 6

Nate
Nate

Reputation: 4754

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.

Upvotes: 4

Mirko N.
Mirko N.

Reputation: 10567

It may be ugly, but I think that's the only way to do it. You can use IOUtils.toString() from Commons-IO though without having to write your own code.

Upvotes: 0

Related Questions