How can I get an HTTP response body as a string?
Here are two examples from my working project.
Using
EntityUtils
andHttpEntity
HttpResponse response = httpClient.execute(new HttpGet(URL));HttpEntity entity = response.getEntity();String responseString = EntityUtils.toString(entity, "UTF-8");System.out.println(responseString);
Using
BasicResponseHandler
HttpResponse response = httpClient.execute(new HttpGet(URL));String responseString = new BasicResponseHandler().handleResponse(response);System.out.println(responseString);
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);
Update: 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.
Here's an example from another simple project I was working on using the httpclient library from Apache:
String response = new String();List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);nameValuePairs.add(new BasicNameValuePair("j", request));HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);HttpPost httpPost = new HttpPost(mURI);httpPost.setEntity(requestEntity);HttpResponse httpResponse = mHttpClient.execute(httpPost);HttpEntity responseEntity = httpResponse.getEntity();if(responseEntity!=null) { response = EntityUtils.toString(responseEntity);}
just use EntityUtils to grab the response body as a String. very simple.