【java】hutool发送http请求,配置ssl忽略

1.发送请求


import cn.hutool.http.HttpRequest;
/**
 * cf
 */
public class TqOdpServiceClient {

     private static String url="url";;
     public static String execute(String http,String params,String auth) {
         String result2 = HttpRequest.post(http+url)
                 .header("Authorization", auth)
                 .header("Content-Type", "application/json;charset=UTF-8").setSSLSocketFactory(SSLUtils.getSSLSocketFactory())
                 .body(params)
                 .execute().body();
         return result2;
     }
}

2.配置ssl忽略

/**
 * @author cf
 * @date 2023/7/3下午 1:06
 */
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLUtils {
    /**
     * 忽略https证书验证
     * @return
     */
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    //检查客户端证书,若不信任该证书抛出异常,咱们自己就是客户端不用检查
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }
                    //检查服务器的证书,若不信任该证书抛出异常,可以不检查默认都信任
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }
                    //返回受信任的X509证书数组
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }
}

你可能感兴趣的:(Java,java,http,ssl)