What's the recommended way to get the HTTP response as a String when using Apache's HTTP Client?

大憨熊 提交于 2019-11-30 11:18:19

You can use EntityUtils#toString() for this.

// ...
HttpResponse response = client.execute(get);
String responseAsString = EntityUtils.toString(response.getEntity());
// ...
Pedro Nunes

You need to consume the response body and get the response:

BufferedReader br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent()));

And then read it:

String readLine;
String responseBody = "";
while (((readLine = br.readLine()) != null)) {
  responseBody += "\n" + readLine;
}

The responseBody now contains your response as string.

(Don't forget to close the BufferedReader in the end: br.close())

You can do something like:

Reader in = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

Using the reader you will be able to build your string. But if you are using SAX you can give the stream to the parser directly. This way you will not have to create the string and your memory footprint will be lower too.

In terms of conciseness of code it might be using the Fluent API like this:

import org.apache.http.client.fluent.Request;
[...]
String result = Request.Get(uri).execute().returnContent().asString();

The documentation warns though that this approach is not ideal in terms of memory consumption.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!