java HttpAsyncClient 的简单使用

maven依赖:

<dependency>  
    <groupId>org.apache.httpcomponents</groupId>  
    <artifactId>httpclient</artifactId>  
    <version>4.5.2</version>  
</dependency>  

<dependency>  
    <groupId>org.apache.httpcomponents</groupId>  
    <artifactId>httpcore</artifactId>  
    <version>4.4.5</version>  
</dependency>  

<dependency>  
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore-nio</artifactId>
    <version>4.4.5</version>
</dependency>  

<dependency>  
    <groupId>org.apache.httpcomponents</groupId>  
    <artifactId>httpasyncclient</artifactId>  
    <version>4.1.2</version>  
</dependency>

多次异步请求:

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class Test {

	public static void main(String[] args) {
		final RequestConfig requestConfitg = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
		final CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfitg).build();

		// CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
		httpClient.start();

		HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.baidu.com/"), new HttpGet("http://www.google.com/") };
		final CountDownLatch latch = new CountDownLatch(requests.length);

		for (final HttpGet request : requests) {
			httpClient.execute(request, new FutureCallback<HttpResponse>() {
				public void completed(final HttpResponse response) {
					latch.countDown();
					System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
				}

				public void failed(final Exception ex) {
					latch.countDown();
					ex.printStackTrace();
					System.out.println(request.getRequestLine() + "->" + ex);
				}

				public void cancelled() {
					latch.countDown();
					System.out.println(request.getRequestLine() + "cancelled");
				}
			});
		}
		System.out.println("Doing...");
		try {
			latch.await();
			System.out.println("Shutting Down");
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		System.out.println("Finish!");
	}
}

其中涉及CountDownLatch的使用,不清楚的童鞋可以访问CountDownLatch用法 获取使用详解

执行结果:
在这里插入图片描述

原文地址:https://www.cnblogs.com/gmhappy/p/13457032.html