`

HttpAsyncClient

阅读更多
参考:
http://wangxinchun.iteye.com/blog/2136254
http://wangxinchun.iteye.com/blog/2156660
http://wangxinchun.iteye.com/blog/2166837

调用http接口,是否可以异步?
答案当然是可以。

方案1:
httpclient+new Thread

/**
 * 使用thread + http 实现异步
 * @author wangxinchun1988@163.com
 * @date 2014-12-16下午5:29:26
 */
public class AsyncHttpClientUtil {
	public static void main(String[] args) throws Exception {
		HttpTask task = new HttpTask();
		task.setUrl("http://www.baidu.com");
		Thread t = new Thread(task);
		t.start();
		t.join();
		System.out.println(task.getData());
	}
	
	public static class HttpTask implements Runnable{
		private String url;
		private String data;

		public void run() {
			System.out.println(url);
			// 模拟请求http返回的结果
			data = "http response " + url;
		}

		public String getData() {
			return data;
		}

		public void setUrl(String url) {
			this.url = url;
		}
	}
}



优化版本:
/**
 * 使用thread + http 实现异步
 * 
 * @author wangxinchun1988@163.com
 * @date 2014-12-16下午5:29:26
 */
public class AsyncHttpClientUtil2 {
	public static void main(String[] args) throws Exception {
		CountDownLatch latch = new CountDownLatch(1);
		HttpTask task = new HttpTask(latch);
		task.setUrl("http://www.baidu.com");
		Thread t = new Thread(task);
		t.start();
		latch.await();
		System.out.println(task.getData());
	}

	public static class HttpTask implements Runnable {
		private String url;
		private String data;
		private CountDownLatch latch;

		public HttpTask(CountDownLatch latch) {
			this.latch = latch;
		}

		public void run() {
			System.out.println(url);
			// 模拟请求http返回的结果
			data = "http response " + url;
			latch.countDown();
		}

		public String getData() {
			return data;
		}

		public void setUrl(String url) {
			this.url = url;
		}
	}
}


方案2
使用apache 的AsyncHttpClient 方案
也是本次讲解的重点
maven 引用:
<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore-nio</artifactId>
			<version>4.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpasyncclient</artifactId>
			<version>4.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpasyncclient-cache</artifactId>
			<version>4.0.2</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.6</version>
		</dependency>
	</dependencies>



使用方式1:(适合调用后很快就会通过引用获取数据)
/**
 * 使用CloseableHttpAsyncClient返回Future<HttpResponse> 实现异步
 * 
 * @author wangxinchun1988@163.com
 * @date 2014-12-16下午5:29:26
 */
public class AsyncHttpClientUtil3 {
	   public static void main(String[] args) throws Exception {
	        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	        try {
	            // Start the client
	            httpclient.start();
	            // Execute request
	            final HttpGet request1 = new HttpGet("http://www.baidu.com/");
	            Future<HttpResponse> future = httpclient.execute(request1, null);
	            // and wait until response is received
	            HttpResponse response1 = future.get();
	            System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine() + " \n" 
	            + EntityUtils.toString(response1.getEntity()));
	        }catch(Exception e){
	        	e.printStackTrace();
	        }finally{
	        	if(httpclient != null){
	        		httpclient.close();
	        	}
	        }
	   }
}


方式2:(适合在回调存储特定的数据)
public class AsyncHttpClientUtil4 {
	public static void main(String[] args) throws Exception {
		CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		final CountDownLatch latch1 = new CountDownLatch(1);
		final HttpGet request2 = new HttpGet("http://www.baidu.com/");
		final ObjectHolder<HttpResponse> holder = new ObjectHolder<HttpResponse>();
		httpclient.execute(request2, new FutureCallback<HttpResponse>() {

			public void completed(final HttpResponse response2) {
				holder.setData(response2);
				System.out.println(request2.getRequestLine() + "->"+ response2.getStatusLine());
				latch1.countDown();
			}

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

			public void cancelled() {
				latch1.countDown();
				System.out.println(request2.getRequestLine() + " cancelled");
			}
		});
		latch1.await();
		HttpResponse response = holder.getData();
		System.out.println(EntityUtils.toString(response.getEntity()));
	}

	public static class ObjectHolder<T> {
		private T data;

		public T getData() {
			return data;
		}

		public void setData(T data) {
			this.data = data;
		}
	}
}


进阶批量:
public class AsyncClientHttpExchangeFutureCallback {

    public static void main(final String[] args) throws Exception {
        RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(3000) .setConnectTimeout(3000).build();
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setDefaultRequestConfig(requestConfig).build();
        try {
            httpclient.start();
            final HttpGet[] requests = new HttpGet[] {
                    new HttpGet("http://www.apache.org/"),
                    new HttpGet("https://www.verisign.com/"),
                    new HttpGet("http://www.google.com/")
            };
            final CountDownLatch latch = new CountDownLatch(requests.length);
            final Map<String,HttpResponse> resultContain = new HashMap<String,HttpResponse>();
            for (final HttpGet request: requests) {
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        resultContain.put(request.getURI().toString(), response);
                        System.out.println("completed: "+request.getRequestLine() + "->" + response.getStatusLine());
                    }

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

                    public void cancelled() {
                        latch.countDown();
                        System.out.println("cancelled:" +request.getRequestLine() + " cancelled");
                    }

                });
            }
            latch.await();
            
            for(Map.Entry<String, HttpResponse> item : resultContain.entrySet()){
            	System.out.println(item.getKey()+":  "+EntityUtils.toString(item.getValue().getEntity()));
            }
            
            System.out.println("Shutting down");
        } finally {
            httpclient.close();
        }
        System.out.println("Done");
    }

}
1
1
分享到:
评论

相关推荐

    httpasyncclient-4.1.5-API文档-中文版.zip

    赠送jar包:httpasyncclient-4.1.5.jar; 赠送原API文档:httpasyncclient-4.1.5-javadoc.jar; 赠送源代码:httpasyncclient-4.1.5-sources.jar; 赠送Maven依赖信息文件:httpasyncclient-4.1.5.pom; 包含翻译后...

    httpasyncclient-4.1.5-API文档-中英对照版.zip

    赠送jar包:httpasyncclient-4.1.5.jar 赠送原API文档:httpasyncclient-4.1.5-javadoc.jar 赠送源代码:httpasyncclient-4.1.5-sources.jar 包含翻译后的API文档:httpasyncclient-4.1.5-javadoc-API文档-中文...

    HttpAsyncClient异步http工具包

    2. **Future接口**: 发起请求后,HttpAsyncClient会返回一个`Future`对象,你可以通过这个对象来查询请求的状态,或者在响应准备就绪时获取响应。 3. **Callback机制**: 你可以提供一个`HttpContext`和`...

    httpasyncclient-4.1.3.zip

    HttpAsyncClient 4.1.3版本是该库的一个稳定版本,包含了重要的改进和修复,旨在提高性能和稳定性。主要特点如下: 1. **非阻塞I/O**:HttpAsyncClient 使用NIO(Non-blocking I/O)模型,允许在单个线程中处理多个...

    HttpAsyncClient 4.1 异步HttpCLient

    HttpAsyncClient基于事件驱动的编程模型,使用非阻塞 I/O 模型。HttpAsyncClient 并不是要替换 Apache 的 HttpClient ,二者是互补关系,在一些需要进行大量并发连接的客户端以及对性能要求比较高的场景下,...

    httpasyncclient jar包

    《深入理解HTTP异步客户端:httpasyncclient-4.0-beta4.jar》 在现代的Web应用程序开发中,高效地处理HTTP请求与响应是至关重要的。Apache HttpClient项目提供了一个强大的工具集,其中就包括了HTTP异步客户端——...

    HttpAsyncClient 异步httpClient和同步httpClient连接池的工具类 包含jar

    HttpAsyncClient连接池的使用,项目中频繁发送http请求,同步http阻塞主线程,影响性能,使用 HttpAsyncClient可使性能提高,这里配合连接池使用,效果更好,同时还附带同步httpClient的连接池使用

    httpasyncclient-4.1.jar

    httpasyncclient-4.1.jar ,java异步处理官网示例代码用jar,专为懒人提供,顺便挣点积分。

    httpasyncclient-4.0-beta3.jar

    httpasyncclient-4.0-beta3.jar 用于webservice开发

    基于java的开发源码-异步HTTP客户端开发包 HttpAsyncClient.zip

    基于java的开发源码-异步HTTP客户端开发包 HttpAsyncClient.zip 基于java的开发源码-异步HTTP客户端开发包 HttpAsyncClient.zip 基于java的开发源码-异步HTTP客户端开发包 HttpAsyncClient.zip 基于java的开发源码-...

    基于java的异步HTTP客户端开发包 HttpAsyncClient.zip

    1. **初始化与配置**:在使用HttpAsyncClient之前,需要先创建一个HttpClientBuilder实例,并对其进行配置,如设置连接池大小、超时时间、重试策略等。然后调用build()方法生成HttpAsyncClient实例。 2. **异步请求...

    异步HTTP客户端开发包 HttpAsyncClient

    在使用HttpAsyncClient时,开发者首先需要创建一个`CloseableHttpAsyncClient`实例,并进行初始化。这通常涉及到设置连接池大小、超时时间、重试策略等配置。然后,你可以通过`execute`方法发送一个或多个HTTP请求,...

    java源码:异步HTTP客户端开发包 HttpAsyncClient.rar

    本篇将深入探讨HttpAsyncClient的核心概念、关键API以及实际应用中的使用技巧。 1. **HttpAsyncClient简介** HttpAsyncClient是Apache HttpClient库的一部分,它支持基于I/O多路复用技术的异步HTTP操作。这种设计...

    基于Java的异步HTTP客户端开发包 HttpAsyncClient.zip

    HttpAsyncClient库基于Apache HttpClient 4.x系列,它提供了与Java标准库中的`java.net.HttpURLConnection`不同的API,主要关注异步操作。这个库的核心理念是通过使用事件驱动模型和回调机制,避免了线程被长时间...

    基于Java的实例源码-异步HTTP客户端开发包 HttpAsyncClient.zip

    2. **HttpAsyncClient模块**:HttpAsyncClient是HttpClient库的一部分,专注于异步非阻塞I/O操作。它基于Java NIO(非阻塞I/O)API,允许开发者在单个线程中并发处理多个HTTP请求,提高了系统性能和响应速度。 3. *...

    httpasyncclient-4.1.4.jar

    java运行依赖jar包

    httpasyncclient-4.1.4-sources.jar

    java运行依赖jar包

    httpasyncclient-4.0-beta4.jar、httpcore-4.3.2.jar和httpmime-4.3.5.jar

    1. **HttpAsyncClient 4.0-beta4**: - `httpasyncclient-4.0-beta4.jar`是Apache HttpClient的一个扩展,专注于非阻塞I/O和异步处理,以实现高性能的HTTP/1.1通信。它基于NIO(非阻塞I/O)和回调机制,允许开发者...

    httpasyncclient-4.0-beta3

    http协议开发包之一

Global site tag (gtag.js) - Google Analytics