1

POM文件引入httpclient

<!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

http 请求工具

package com.raytoo.common.toolbox.http;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http 工具
 */
public class HttpTool {
    
    private static Logger logger = LoggerFactory.getLogger(HttpTool.class);
    
    private static String ENCODING = "UTF-8";
    
    private static String CONTENT_TYPE = "application/json";
    
    /**
     * 发送POST请求,参数是JSON
     */
    public static String requestPost(String url, String jsonParam){
        logger.info("HttpTool.requestPost 开始 请求url:" + url + ", 参数:" + jsonParam);
        //创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        
        //配置请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.DEFAULT)
                .setExpectContinueEnabled(true)
                .setSocketTimeout(5000)  
                .setConnectTimeout(5000)  
                .setConnectionRequestTimeout(5000)  
                .build();
        
        httpPost.setConfig(requestConfig);
        
        String respContent = null;
            
        //设置参数和请求方式
        StringEntity entity = new StringEntity(jsonParam,ENCODING);//解决中文乱码问题    
        entity.setContentEncoding(ENCODING);    
        entity.setContentType(CONTENT_TYPE);  
        
        httpPost.setEntity(entity);
            
        HttpResponse resp;
        try {
            //执行请求
            resp = client.execute(httpPost);
            if(resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity responseObj = resp.getEntity();
                respContent = EntityUtils.toString(responseObj,"UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("HttpTool.requestPost 异常 请求url:" + url + ", 参数:" + jsonParam + ",异常信息:" + e);
        }
        logger.info("HttpTool.requestPost 结束 请求url:" + url + ", 参数:" + jsonParam + "");
        //返回数据
        return respContent;
    }
}

异步执行HTTP请求和并发测试demo

package com.raytoo.common.toolbox.http;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

/**
 * 异步执行HTTP请求
 */
public class HttpCallable implements Callable<String> {
    
    private String url;
    
    private String jsonParams;
    
    public HttpCallable(String url, String jsonParams){
        this.url = url;
        this.jsonParams = jsonParams;
    }

    /**
     * 执行并返回结果
     */
    @Override
    public String call() throws Exception {
        return HttpTool.requestPost(url, jsonParams);
    }
    
    /**
     * 模拟并发测试
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //模拟并发数
        int concurrencyNumber = 1000;
        
        List<String>  resList = Lists.newArrayList();
        
        //执行线程池
        ExecutorService ex = Executors.newFixedThreadPool(100);
        
        String url = "www.baidu.com";
        Map<String, String> mapPatam = new HashMap<>();
        mapPatam.put("name", "测试");
        
        
        for(int i =0 ; i< concurrencyNumber; i++){
            Future<String> callRes = ex.submit(new HttpCallable(url, JSON.toJSONString(mapPatam)));
            resList.add(i + ">>>" + callRes.get());
        }
        
        for(String s : resList){
            System.out.println("------>" + s);
        }
    }

}

麦冬
315 声望13 粉丝

越成熟的稻穗,越饱满厚实