http请求封装工具类

import org.apache.*;

public class HttpClientHelper {

    private static final String APPLICATION_X_WWW_FORM_URLENCODED = ContentType.APPLICATION_FORM_URLENCODED.getMimeType();
    private static final String APPLICATION_JSON = ContentType.APPLICATION_JSON.getMimeType();

    private static final String CHARTSET = "UTF-8";

    private static final int CONNTIMEOUT = 60000;

    private static final int READTIMEOUT = 60000;

    private static final int MAX_RETRY = 3;

    private static CloseableHttpClient httpClient = null;

    static {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();

        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf)
                .register("https", sslsf).build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

        // 将最大连接数增加到1000
        cm.setMaxTotal(50);

        // 将每个路由基础的连接增加到100
        cm.setDefaultMaxPerRoute(10);

        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static <T> T postForObject(String url, String body, Class<T> toClass) throws IOException {
        String res = post(url, body, APPLICATION_X_WWW_FORM_URLENCODED, CHARTSET, CONNTIMEOUT, READTIMEOUT);
        return JsonUtils.parse(res, toClass);
    }

    public static Map<?, ?> postForMap(String url, String body) throws IOException {
        String res = post(url, body, APPLICATION_X_WWW_FORM_URLENCODED, CHARTSET, CONNTIMEOUT, READTIMEOUT);
        return JsonUtils.parse(res,Map.class);
    }

    public static String post(String url, String body) throws IOException {
        return post(url, body, APPLICATION_X_WWW_FORM_URLENCODED, CHARTSET, CONNTIMEOUT, READTIMEOUT);
    }

    public static String post(String url, String body, String charset, Integer connTimeout, Integer readTimeout) throws IOException {
        return post(url, body, APPLICATION_X_WWW_FORM_URLENCODED, charset, connTimeout, readTimeout);
    }

    public static <T> T postJsonData(String url, String body, Class<T> toClass) throws IOException {
        String res = post(url, body, APPLICATION_JSON, CHARTSET, CONNTIMEOUT, READTIMEOUT);
        return JsonUtils.parse(res, toClass);
    }

    public static <T> T postFormData(String url, Map<String, String> params, Class<T> toClass) throws IOException {
        String res = postForm(url, params, null, CONNTIMEOUT, READTIMEOUT);
        return JsonUtils.parse(res, toClass);
    }

    public static <T> T postFormData(String url, Map<String, String> params, Map<String, String> headers, Class<T> toClass) throws IOException {
        String res = postForm(url, params, headers, CONNTIMEOUT, READTIMEOUT);
        return JsonUtils.parse(res, toClass);
    }

    public static String postFormData(String url, Map<String, String> params) throws IOException {
        return postForm(url, params, null, CONNTIMEOUT, READTIMEOUT);
    }

    public static String postFormData(String url, Map<String, String> params, Integer connTimeout, Integer readTimeout) throws IOException {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static <T> T getForObject(String url, Class<T> toClass) throws UnsupportedOperationException, IOException {
        String res = get(url, CHARTSET, CONNTIMEOUT, READTIMEOUT);
        return JsonUtils.parse(res, toClass);
    }

    public static String get(String url) throws IOException {
        return get(url, CHARTSET, CONNTIMEOUT, READTIMEOUT);
    }

    public static String get(String url, String charset) throws IOException {
        return get(url, charset, CONNTIMEOUT, READTIMEOUT);
    }

    public static String post(String url, String body, String mimeType, String charset, Integer connTimeout, Integer readTimeout)
            throws IOException {
        HttpPost post = new HttpPost(url);
        String result = null;
        try {
            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
                post.setEntity(entity);
            }
            RequestConfig customReqConfig = getCustomReqConfig(connTimeout, readTimeout);
            post.setConfig(customReqConfig);
            HttpResponse res = httpClient.execute(post);
            result = EntityUtils.toString(res.getEntity(), charset);
        } finally {
            post.releaseConnection();
        }
        return result;
    }

    public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,
                                  Integer readTimeout) throws IOException {
        HttpPost post = new HttpPost(url);
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
                post.setEntity(entity);
            }
            if (headers != null && !headers.isEmpty()) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            RequestConfig customReqConfig = getCustomReqConfig(connTimeout, readTimeout);
            post.setConfig(customReqConfig);
            HttpResponse res = httpClient.execute(post);
            return EntityUtils.toString(res.getEntity(), CHARTSET);
        } finally {
            post.releaseConnection();
        }
    }

    public static String get(String url, String charset, Integer connTimeout, Integer readTimeout) throws UnsupportedOperationException,
            IOException {
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            RequestConfig customReqConfig = getCustomReqConfig(connTimeout, readTimeout);
            get.setConfig(customReqConfig);
            HttpResponse res = httpClient.execute(get);
            result = EntityUtils.toString(res.getEntity(), charset);
        } finally {
            get.releaseConnection();
        }
        return result;
    }

    private static RequestConfig getCustomReqConfig(Integer connTimeout, Integer readTimeout) {
        Builder customReqConf = RequestConfig.custom();
        if (connTimeout != null) {
            customReqConf.setConnectTimeout(connTimeout);
        }
        if (readTimeout != null) {
            customReqConf.setSocketTimeout(readTimeout);
        }
        return customReqConf.build();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值