How can I get an http response body as a string in Java?

Daniel Shaulov picture Daniel Shaulov · Apr 24, 2011 · Viewed 467.8k times · Source

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?

Answer

spideringweb picture spideringweb · Dec 6, 2012

Here are two examples from my working project.

  1. Using EntityUtils and HttpEntity

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    
  2. Using BasicResponseHandler

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);