【工具笔记】java http请求 异步访问工具 httpclient httpasyncclient

该博客介绍了如何使用Apache HttpClient库创建并执行Java的异步HTTP POST请求。通过示例代码展示了如何配置请求超时、设置请求头、处理响应内容,并利用CountDownLatch进行同步控制,确保所有请求完成后再继续后续操作。此工具类适用于批量异步调用HTTP接口的场景。
摘要由CSDN通过智能技术生成
   		<dependency>
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpasyncclient</artifactId>
		    <version>4.1.5</version>
		</dependency>
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * java http请求 异步访问工具<br/>
 * CountDownLatch
 * @author 孔小胖子
 *
 */
public class AsyncHttpUtil {
	private static final RequestConfig requestConfig = RequestConfig.custom()  
			.setConnectTimeout(3000)
			.setConnectionRequestTimeout(3000)  
			.setSocketTimeout(3000).build(); 
	
	public static HttpPost createHttpPost(String url, List<NameValuePair> nvps, String callbackId, String contentType, String chartSet){
		if(nvps==null) {
			nvps = new ArrayList<NameValuePair>();
		}
		for(NameValuePair nvp : nvps){
			if("callbackId".equals(nvp.getName())) {
				nvps.remove(nvp);
				break;
			}
		}
		nvps.add(new BasicNameValuePair("callbackId", callbackId==null||"".equals(callbackId)?UUID.randomUUID().toString():callbackId));
		HttpPost post = new HttpPost(url);
		//设置请求头    这里根据个人来定义
		post.setConfig(requestConfig);
	        
		post.addHeader("Content-type", contentType==null?"application/x-www-form-urlencoded":contentType);
		StringEntity stringEntity = new UrlEncodedFormEntity(nvps, Charset.forName(chartSet==null?"utf-8":chartSet));
		stringEntity.setContentEncoding(chartSet==null?"utf-8":chartSet);
	   	stringEntity.setContentType(contentType==null?"application/x-www-form-urlencoded8":contentType);
	   	post.setEntity(stringEntity);
	   	return post;
	}
	
	public static Map<String, JSONObject> requestPostAsync(List<HttpPost> requests){
		final Map<String, JSONObject> res = new HashMap<String, JSONObject>();
        CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
        client.start();
        final CountDownLatch latch = new CountDownLatch(requests.size());
        for(HttpPost post : requests) {
            //执行
            client.execute(post, new FutureCallback<HttpResponse>() {
                //执行异步操作  请求完成后
                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    //响应内容
                    int code = response.getStatusLine().getStatusCode();
                    if (code == 200) {
                        HttpEntity entity = response.getEntity();
                        try {
                            String result = EntityUtils.toString(entity);
                            //json数据格式
                            JSONObject resObj = JSON.parseObject(result);
                            System.out.println(resObj.toJSONString());
                            //接口返回callbackId
                            String callbackId = resObj.getString("callbackId");
//                            System.out.println("-------"+(System.currentTimeMillis()-nowtime)+"    "+callbackId);
                            if(callbackId!=null) {
                            	res.put(callbackId, resObj);
                            }else {
                            	res.put(UUID.randomUUID().toString(), resObj);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            //输出响内容
                            System.out.println(response.getStatusLine().getStatusCode() + "  " + EntityUtils.toString(response.getEntity(), "UTF-8"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
     
                //请求失败处理
                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println("访问失败");
                }
     
                //请求取消后处理
                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println("访问失败");
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //关闭
        try {
            client.close();
        } catch (IOException e) {
        	e.printStackTrace();
        }
        return res;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孔小胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值