基于线程池的HttpUtil

一.支持Get请求传Text格式
1.porm文件

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

2.需要自定义Entity,使get可传Text

import java.net.URI;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
    private final static String METHOD_NAME = "GET";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpGetWithEntity() {
        super();
    }

    public HttpGetWithEntity(final URI uri) {
        super();
        setURI(uri);
    }

    HttpGetWithEntity(final String uri) {
        super();
        setURI(URI.create(uri));
    }

}

3.Util类

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.hongcheng.Constants;
import com.hongcheng.config.PlatformConf;
import com.hongcheng.exception.GlobalException;
import com.hongcheng.result.CodeMsg;
import com.hongcheng.result.CodeNumEnum;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.IdleConnectionEvictor;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {
    private HttpUtils() {}

    private static final Logger LOG = LoggerFactory.getLogger("job");

    private static final Integer CLIENT_SOCKET_TIMEOUT = PlatformConf.getInt(Constants.HTTP_CLIENT_SOCKET_TIMEOUT);
    private static final Integer CLIENT_CONNECTION_TIMEOUT = PlatformConf.getInt(Constants.HTTP_CLIENT_CONNECTION_TIMEOUT);
    private static final Integer CLIENT_CONNECTION_REQ_TIMEOUT = PlatformConf.getInt(Constants.HTTP_CLIENT_CONNECTION_REQ_TIMEOUT);
    private static final String ENCODEING = "UTF-8";

    private static PoolingHttpClientConnectionManager gcm = null;

    private static IdleConnectionEvictor idleThread = null;

    private static CloseableHttpClient httpClient = null;

    static {
        init();
    }

    public static void init() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                                                         .register("http", PlainConnectionSocketFactory.getSocketFactory())
                                                         .register("https", SSLConnectionSocketFactory.getSocketFactory())
                                                         .build();

        gcm = new PoolingHttpClientConnectionManager(registry);
        gcm.setMaxTotal(80);
        gcm.setDefaultMaxPerRoute(80);

        RequestConfig requestConfig = RequestConfig.custom()
                                          .setConnectTimeout(CLIENT_CONNECTION_TIMEOUT)                   // 设置连接超时
                                          .setSocketTimeout(CLIENT_SOCKET_TIMEOUT)                     // 设置读取超时
                                          .setConnectionRequestTimeout(CLIENT_CONNECTION_REQ_TIMEOUT)  // 设置从连接池获取连接实例的超时
                                          .build();

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClient = httpClientBuilder
                         .setConnectionManager(gcm)
                         .setConnectionManagerShared(true)
                         .setDefaultRequestConfig(requestConfig)
                         .build();

        idleThread = new IdleConnectionEvictor(gcm, 30, TimeUnit.SECONDS);
        idleThread.start();


    }

    public static String doGetWithBodyText(String url, Map<String, String> headerMap, String param, String name) throws GlobalException {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            long startTime = System.currentTimeMillis();   //获取开始时间
            HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
            HttpEntity httpEntity = new StringEntity(param, ContentType.DEFAULT_TEXT);
            httpGetWithEntity.setEntity(httpEntity);
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CLIENT_CONNECTION_TIMEOUT)// 设置连接主机服务超时时间
                                              .setConnectionRequestTimeout(CLIENT_CONNECTION_REQ_TIMEOUT)// 设置连接请求超时时间
                                              .setSocketTimeout(CLIENT_SOCKET_TIMEOUT)// 设置读取数据连接超时时间
                                              .build();
            // 为httpPost实例设置配置
            httpGetWithEntity.setConfig(requestConfig);

            //设置请求头
            if (headerMap != null && headerMap.size() > 0) {
                headerMap.keySet().forEach(str -> httpGetWithEntity.addHeader(str, headerMap.get(str)));
            }
            //执行请求操作,并拿到结果(同步阻塞)
            response = httpClient.execute(httpGetWithEntity);

            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();


            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
            long endTime = System.currentTimeMillis(); //获取结束时间
            LOG.info("{} request url running time:{} ms", name, endTime - startTime);
            return result;
        } catch (IOException e) {
            LOG.error("http client get error", e);
            throw new GlobalException(new CodeMsg(CodeNumEnum.SERVER_ERROR, "连接异常"));
        } finally {
            //关闭资源
            IOUtils.closeQuietly(response, e -> LOG.error("Rest exception: ", e));
        }
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值