HttpAsyncClient

参考:
[url]http://wangxinchun.iteye.com/blog/2136254[/url]
[url]http://wangxinchun.iteye.com/blog/2156660[/url]
[url]http://wangxinchun.iteye.com/blog/2166837[/url]

调用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");
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值