HttpUtils.java 4.65 KB
package cn.com.glsx.wechatbuild.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

    /**
     * 发送 HTTP POST 请求,并强制使用 TLS 1.2
     *
     * @param url      请求的目标 URL
     * @param entity   请求体内容(JSON、XML 等)
     * @param timeout  超时时间(单位:毫秒)
     * @param headers  请求头参数
     * @return 响应内容字符串
     * @throws Exception 如果请求失败或出现异常
     */
    public static String post(String url, String entity, Map<String, String> headers) throws Exception {
        // 强制使用 TLS 1.2
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);

        // 创建支持 TLS 1.2 的 SSL 连接工厂
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1.2"}, // 强制使用 TLS 1.2
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()
        );

        // 使用自定义的 SSL 连接工厂创建 HttpClient
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build()) {

            // 创建 POST 请求
            HttpPost httpPost = new HttpPost(url);

            // 设置请求体
            if (entity != null && !entity.isEmpty()) {
                StringEntity requestEntity = new StringEntity(entity, "UTF-8");
                requestEntity.setContentType("application/json"); // 默认设置为 JSON 格式
                httpPost.setEntity(requestEntity);
            }

            // 设置请求头
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }

            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(60000) // 连接超时时间
                    .setSocketTimeout(60000)  // 读取超时时间
                    .build();
            httpPost.setConfig(requestConfig);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
    }

    public static String get(String url) throws Exception {
        // 强制使用 TLS 1.2
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);

        // 创建支持 TLS 1.2 的 SSL 连接工厂
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1.2"}, // 强制使用 TLS 1.2
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()
        );

        // 使用自定义的 SSL 连接工厂创建 HttpClient
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build()) {

            // 创建 POST 请求
            HttpGet httpGet = new HttpGet(url);
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(60000) // 连接超时时间
                    .setSocketTimeout(60000)  // 读取超时时间
                    .build();
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("accept", "application/json");
            // 执行请求并获取响应
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                return responseHandler.handleResponse(response);
            }
        }
    }
}