我有以下方法,它使用Apache客户端将异步GET发送到给定的URI,并通过响应返回Future。
CloseableHttpAsyncClient实现了关闭,因此我使用了try/resource。
public static Future<HttpResponse> sendAsyncGet(String uri) throws IOException {
try (CloseableHttpAsyncClient asyncHttpClient = HttpAsyncClients.createDefault()) {
asyncHttpClient.start();
HttpGet httpGet = new HttpGet(uri);
return asyncHttpClient.execute(httpGet, null);
}
下面您可以看到使用情况:
Future<HttpResponse> future = sendAsyncGet("http://www.apache.org");
future.get(3, TimeUnit.SECONDS);
问题是,当我调用get时,它不会返回所需的HttpResponse。如果我使用重载的get()方法,它将等待超时,或者永远等待。我想这是因为try/resource没有被正确地释放。
如何改进给定的方法/代码以使其能够正确使用:具有方法主体中包含的try/资源结构的未来?
更新:
这是maven依赖关系:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.1</version>
<scope>test</scope>
</dependency>
发布于 2016-03-12 12:08:30
在收到响应之前,使用资源尝试将关闭异步客户端。
您可能希望从传递给execute调用的将来回调中关闭异步客户机。
public static Future<HttpResponse> sendAsyncGet(String uri) throws IOException {
final CloseableHttpAsyncClient asyncHttpClient;
asyncHttpClient = HttpAsyncClients.createDefault();
asyncHttpClient.start();
return asyncHttpClient.execute(new HttpGet(uri), new FutureCallback<HttpResponse>() {
private void close() {
try {
asyncHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void completed(HttpResponse response) {
close();
System.out.println("completed");
}
@Override
public void failed(Exception e) {
close();
e.printStackTrace();
}
@Override
public void cancelled() {
close();
System.out.println("cancelled");
}
});
}
https://stackoverflow.com/questions/35961356
复制