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:
ByteArrayOutputStream
and then convert those bytes to a String with a String constructorBoth of these feel a bit ugly. Would you recommend choosing one of these or something else?
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.
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.
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.
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.
System.out.println( EntityUtils.toString(httpResponse.getEntity()) );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With