HttpAsyncClient

HttpAsyncClient

HttpAsyncClient 是一个异步的 HTTP 客户端开发包,基于 HttpCore NIO 和 HttpClient 组件。
HttpAsyncClient 的出现并不是为了替换 HttpClient,而是作为一个补充用于需要大量并发连接,对性能要求非常高的基于HTTP的原生数据通信,而且提供了事件驱动的 API。

代码示例:

       public Vector<Long> Gets(List<String> urls)
throws IOReactorException, InterruptedException {
List<HttpGet> requests = new ArrayList<HttpGet>();
for (String url : urls) {
HttpGet get = new HttpGet(url);
requests.add(get);
}
final Vector<Long> dataPackages = new Vector<Long>();
HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.getParams().setIntParameter("http.socket.timeout", 5000)
.setIntParameter("http.connection.timeout", 5000)
.setIntParameter("http.socket.buffer-size", 8192)
.setBooleanParameter("http.tcp.nodelay", true);
final CountDownLatch latch = new CountDownLatch(requests.size());
httpclient.start();
try {
for (final HttpGet request : requests) {
httpclient.execute(request, new FutureCallback<HttpResponse>() {

@Override
public void completed(HttpResponse result) {
String statInfo = "";
try {
statInfo = result.getFirstHeader("statInfo").getValue();
if (statInfo != null) {
Long size = Long.parseLong(statInfo.split(",")[0].split(":")[1]);
dataPackages.add(size);
}
} catch (Exception e) {
System.out.println(e);
System.out.println(statInfo);
}
latch.countDown();
}

@Override
public void failed(Exception ex) {
latch.countDown();
}

@Override
public void cancelled() {
latch.countDown();
}
});
}
latch.await();
} finally {
httpclient.shutdown();
}
return dataPackages;
}

 


依赖的pom,
httpasyncclient已经有4.0-beta3版本了
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpasyncclient</artifactId>
    <version>4.0-beta1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2-beta1</version>
</dependency>


你可能感兴趣的:(HttpAsyncClient)