Hem*_*ant 4 apache-httpclient-4.x
我正在为httpclient使用apache httpcompnonents库.我想在一个多线程应用程序中使用它,在这个应用程序中,线程数量将非常高,并且会有频繁的http调用.这是我用来在执行调用后读取响应的代码.
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
Run Code Online (Sandbox Code Playgroud)
我只想确认这是阅读响应的最有效方式吗?
谢谢,Hemant
ok2*_*k2c 17
这实际上代表了处理HTTP响应的最低效方式.
您最有可能希望将响应内容消化为某种域对象.那么,以字符串的形式在内存中缓存它有什么意义呢?
处理响应处理的推荐方法是使用ResponseHandler可以通过直接从底层连接流式处理内容的自定义.使用a的额外好处ResponseHandler是它可以完全免于处理连接释放和资源释放.
编辑:修改示例代码以使用JSON
以下是使用HttpClient 4.2和Jackson JSON处理器的示例.Stuff假定您的域对象具有JSON绑定.
ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() {
@Override
public Stuff handleResponse(
final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12854 次 |
| 最近记录: |