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

经博延
2023-12-01
   		<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;
	}
}

 类似资料: