gpt4 book ai didi

apache-httpclient-4.x - apache httpclient - 读取响应的最有效方式

转载 作者:行者123 更新时间:2023-12-03 15:10:02 26 4
gpt4 key购买 nike

我正在为 httpclient 使用 apache httpcompnonents 库。我想在多线程应用程序中使用它,其中线程数会非常高,并且会有频繁的 http 调用。这是我用来在执行调用后读取响应的代码。

HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);

我只是想确认这是阅读回复的最有效方式吗?

谢谢,
赫曼

最佳答案

这实际上代表了处理 HTTP 响应的最低效的方式。
您很可能希望将响应的内容消化成某种领域对象。那么,以字符串的形式在内存中缓冲它有什么意义呢?
处理响应处理的推荐方法是使用自定义 ResponseHandler它可以通过直接从底层连接流式传输内容来处理内容。使用 ResponseHandler 的额外好处是它完全从处理连接释放和资源释放中解脱出来。
编辑:修改示例代码以使用 JSON
这是一个使用 HttpClient 4.2 和 Jackson JSON 处理器的示例。 Stuff假定为您的具有 JSON 绑定(bind)的域对象。

ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() {

@Override
public Stuff handleResponse(
final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
JsonFactory jsonf = new JsonFactory();
InputStream instream = entity.getContent();
// try - finally is not strictly necessary here
// but is a good practice
try {
JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
} finally {
instream.close();
}
}
};
DefaultHttpClient client = new DefaultHttpClient();
Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh);

关于apache-httpclient-4.x - apache httpclient - 读取响应的最有效方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com