java 使用restTemplate请求接口忽略ssl证书校验

目录

  • 1. 使用
  • 2. 忽略ssl证书工具类

1. 使用

在请求之前调用 TrustSslUtil.initDefaultSsl() 方法即可

// 获取需要的请求头
HttpHeaders httpHeaders = new HttpHeaders();

// 设置请求实体
HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);

URI uri = new URI('https://192.168.11.12:8080/auth-api/getTemplate');

// 忽略证书验证
TrustSslUtil.initDefaultSsl();
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, JSONObject.class);
logger.info(">>> [{}] responseEntity: {}", METHOD_NAME, responseEntity);

2. 忽略ssl证书工具类

package com.cn.pro.common.util;

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

/**
 * 忽略证书验证
 */
public class TrustSslUtil {

    public static void initDefaultSsl() {
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            HostnameVerifier hv = (urlHostName, session) -> true;
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509ExtendedTrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[]
                                                               x509Certificates, String s) {
                        }


                        @Override
                        public void checkServerTrusted(X509Certificate[]
                                                               x509Certificates, String s) {
                        }


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


                        @Override
                        public void checkClientTrusted(X509Certificate[]
                                                               x509Certificates, String s, Socket socket) {
                        }


                        @Override
                        public void checkServerTrusted(X509Certificate[]
                                                               x509Certificates, String s, Socket socket) {
                        }


                        @Override
                        public void checkClientTrusted(X509Certificate[]
                                                               x509Certificates, String s, SSLEngine sslEngine) {
                        }


                        @Override
                        public void checkServerTrusted(X509Certificate[]
                                                               x509Certificates, String s, SSLEngine sslEngine) {
                        }
                    }};
            sc.init(null, trustAllCerts, new SecureRandom());


            SSLContext.setDefault(sc);
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(Java,java,ssl,开发语言)