Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I know there used to be a way to get it with apache commons as documented here: http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html and an example here:

http://www.kodejava.org/examples/416.html

but i believe this is deprecated. Is there any other way to make an http get request in java and get the response body as a string and not a stream?

1 Answer

0 votes
by (46k points)

Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:

URL url = new URL("http://www.example.com/");

URLConnection con = url.openConnection();

InputStream in = con.getInputStream();

String encoding = con.getContentEncoding();

encoding = encoding == null ? "UTF-8" : encoding;

String body = IOUtils.toString(in, encoding);

System.out.println(body);

 I changed the example above to use the content encoding from the response if available. Otherwise it'll default to UTF-8 as a best guess, instead of using the local system default.

Browse Categories

...