随笔 - 38,  文章 - 1,  评论 - 2,  阅读 - 13590
复制代码
package com.yonyou.ucf.mdf.sample.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.util.Map;

@Slf4j
public class RequestTool {

    private static final String HEADER_CONTENT_JSON = "application/json";

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

    private static PoolingHttpClientConnectionManager cm = null;

    private static ObjectMapper mapper = new ObjectMapper();

    private static CloseableHttpClient httpClient;

    /**
     * 记录开放平台请求结果
     */
    public static class Response {
        /**
         * 该请求的 http 状态码
         * 200 为正常的返回结果
         */
        private int status;

        /**
         * 请求返回消息
         * 当 status == 200 时会返回 response body 中的字符串
         * 当 status !== 200 时会返回具体的错误信息
         */
        private String result;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }
    }
    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, (TrustStrategy) (x509Certificates, s) -> true);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslsf)
                    .build();

            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(500);
            cm.setDefaultMaxPerRoute(50);

            RequestConfig globalConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(3000)         // 连接池获取连接超时
                    .setConnectTimeout(3000)                   // 连接建立超时
                    .setSocketTimeout(10000)                    // 等待响应超时
                    .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                    .build();
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(globalConfig).build();
        } catch (Exception ignore) {
        }
    }

    private static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public static <T> T doGet(String requestUrl, Map<String, Object> paramMap, Class<T> type) throws Exception {
        return mapper.readValue(doGet(requestUrl, paramMap), type);
    }

    public static <T> T doGet(String requestUrl, Map<String, Object> paramMap, TypeReference<T> typeReference) throws Exception {
        return mapper.readValue(doGet(requestUrl, paramMap), typeReference);
    }

    public static <T> T doPost(String requestUrl, Map<String, Object> requestParam, Map<String, Object> requestBody, Class<T> type) throws Exception {
        return mapper.readValue(doPost(requestUrl, null, requestParam, requestBody), type);
    }

    public static <T> T doPost(String requestUrl, Map<String, String> requestHeader, Map<String, Object> requestParam, Map<String, Object> requestBody, Class<T> type) throws Exception {
        return mapper.readValue(doPost(requestUrl, requestHeader, requestParam, requestBody), type);
    }

    public static String doGet(String requestUrl, Map<String, Object> paramMap) {
        try {
            CloseableHttpClient httpClient = getHttpClient();
            StringBuilder param = new StringBuilder(requestUrl.indexOf("?") > 0 ? "&" : "?");
            if (paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    param.append("&");
                }
                param.deleteCharAt(param.length() - 1);
            }

            HttpGet get = new HttpGet(requestUrl + param);
            String responseString = httpClient.execute(get, response -> EntityUtils.toString(response.getEntity()));
            get.releaseConnection();
            return responseString;
        } catch (Throwable e) {
            log.error("接口调用异常GET: url: {}, paramMap: {}", requestUrl, paramMap, e);
            JSONObject defaultErrorResp = new JSONObject();
            defaultErrorResp.put("code", 500);
            defaultErrorResp.put("success", false);
            defaultErrorResp.put("message", e.getMessage());
            return defaultErrorResp.toString();
        }
    }

    public static String doPost(String requestUrl, Map<String, String> requestHeader, Map<String, Object> requestParam, Map<String, Object> requestBody) {
        try {
            CloseableHttpClient httpClient = getHttpClient();
            StringBuilder param = new StringBuilder(requestUrl.indexOf("?") > 0 ? "&" : "?");
            if (requestParam != null) {
                for (Map.Entry<String, Object> entry : requestParam.entrySet()) {
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    param.append("&");
                }
                param.deleteCharAt(param.length() - 1);
            }

            //创建post请求对象
            HttpPost post = new HttpPost(requestUrl + param);
            //设置请求头
            post.setHeader("Content-Type", "application/json; charset=UTF-8");
            if (requestHeader != null) {
                for (Map.Entry<String, String> header : requestHeader.entrySet()) {
                    post.setHeader(header.getKey(), header.getValue());
                }
            }
            //设置请求体
            if (requestBody != null) {
                StringEntity stringEntity = new StringEntity(JSON.toJSONString(requestBody), "UTF-8");
                post.setEntity(stringEntity);
            }
            String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
            post.releaseConnection();
            return responseString;
        } catch (Throwable e) {
            log.error("接口调用异常POST: url: {}, paramMap: {}, requestBody: {}", requestUrl, requestParam, JSON.toJSONString(requestBody), e);
            JSONObject defaultErrorResp = new JSONObject();
            defaultErrorResp.put("code", 500);
            defaultErrorResp.put("success", false);
            defaultErrorResp.put("message", e.getMessage());
            return defaultErrorResp.toString();
        }
    }
}
复制代码

 

posted on   yang希军  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示