package com.zjsgfa.framework.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class HttpsSkipVerifyUtil {

    // 初始化跳过SSL验证的配置
    static {
        try {
            // 1. 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {}

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {}

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };

            // 2. 初始化SSLContext，信任所有证书
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            // 3. 设置全局SSLContext
            SSLContext.setDefault(sslContext);

            // 4. 设置主机名验证器，跳过主机名校验
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (Exception e) {
            throw new RuntimeException("初始化SSL配置失败", e);
        }
    }

    /**
     * GET请求调用HTTPS接口（跳过SSL验证）
     * @param url HTTPS接口地址
     * @return 接口响应内容
     */
    public static String doGet(String url) {
        return HttpUtil.get(url);
    }

    /**
     * POST请求调用HTTPS接口（跳过SSL验证）
     * @param url HTTPS接口地址
     * @param body 请求体（JSON/表单字符串）
     * @return 接口响应内容
     */
    public static String doPost(String url, String body) {
        return HttpUtil.post(url, body);
    }

    /**
     * 自定义HttpRequest调用HTTPS接口（更灵活的配置）
     * @param url HTTPS接口地址
     * @return 接口响应内容
     */
    public static String customRequest(String url) {
        try (HttpResponse response = HttpRequest.get(url)
                // 可添加header、超时时间等自定义配置
                .header("Content-Type", "application/json")
                .timeout(5000)
                .execute()) {
            return response.body();
        }
    }

    // 测试方法
    public static void main(String[] args) {
        // 测试调用HTTPS接口（替换为实际的HTTPS地址）
        String result = HttpsSkipVerifyUtil.doGet("https://www.baidu.com");
        System.out.println("接口响应：" + result);
    }
}
