java HttpAsyncClient 的简单使用

maven依赖:

<dependency>  
    <groupId>org.apache.httpcomponentsgroupId>  
    <artifactId>httpclientartifactId>  
    <version>4.5.2version>  
dependency>  

<dependency>  
    <groupId>org.apache.httpcomponentsgroupId>  
    <artifactId>httpcoreartifactId>  
    <version>4.4.5version>  
dependency>  

<dependency>  
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpcore-nioartifactId>
    <version>4.4.5version>
dependency>  

<dependency>  
    <groupId>org.apache.httpcomponentsgroupId>  
    <artifactId>httpasyncclientartifactId>  
    <version>4.1.2version>  
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用法 获取使用详解

执行结果:
java HttpAsyncClient 的简单使用_第1张图片

你可能感兴趣的:(java,web)