拿到.pfx证书后如何调用https接口

文章讲述了如何在SpringBoot项目中使用HTTPS进行请求,包括SSLContext的初始化、SSLSocketFactory的获取、X509TrustManager的自定义以及KMSConfig的配置。作者详细展示了如何处理HTTPS连接和证书验证的过程。
摘要由CSDN通过智能技术生成

原文

package com.msfunds.dcs.modules.kms;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

@Component
public class RequestUtil {

    @Autowired
    private KmsConfig kmsConfig;

    private SSLSocketFactory sslFactory = null;

    public String httpsRequest(String url, String method, Object requestBody) {
        try {
            Map<String, String> headers = new HashMap<>(2);
            headers.put("Content-Type", "application/json");
            HttpsURLConnection connection = doHttpRequest(url, method, requestBody, headers);
            String responseBody = getResponseBodyAsString(connection);
            connection.disconnect();
            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private synchronized SSLSocketFactory getSSLFactory(String certPath, String certPassword) throws Exception {
        if (sslFactory == null) {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager(certPath, certPassword)};
            KeyStore truststore = KeyStore.getInstance("JKS");
            truststore.load(new FileInputStream(certPath), certPassword.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(truststore, certPassword.toCharArray());
            sslContext.init(kmf.getKeyManagers(), tm, new java.security.SecureRandom());
            sslFactory = sslContext.getSocketFactory();
        }
        return sslFactory;
    }

    private HttpsURLConnection doHttpRequest(String requestUrl, String method, Object req, Map<String, String> header) throws Exception {
        HttpsURLConnection conn;
        String body = JSON.toJSONString(req);
        if (method == null || method.length() == 0) {
            method = "GET";
        }
        if ("GET".equals(method) && !body.isEmpty()) {
            requestUrl = requestUrl + "?" + body;
        }
        //  直接通过主机认证
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        java.net.URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod(method);

        if (requestUrl.matches("^(https)://.*$")) {
            ((HttpsURLConnection) conn).setSSLSocketFactory(this.getSSLFactory(kmsConfig.getGetCertPath(), kmsConfig.getGetCertPassword()));
        }

        if (header != null) {
            for (String key : header.keySet()) {
                conn.setRequestProperty(key, header.get(key));
            }
        }
        if (!body.isEmpty()) {
            if (!"GET".equals(method)) {
                OutputStream outputStream = conn.getOutputStream();
                OutputStreamWriter wr = new OutputStreamWriter(outputStream);
                wr.write(body);
                wr.close();
            }
        }
        conn.connect();
        return conn;
    }

    private static String getResponseBodyAsString(HttpsURLConnection connection) throws Exception {
        BufferedReader reader = null;
        if (connection.getResponseCode() == 200) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        StringBuilder buffer = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }

    static class MyX509TrustManager implements X509TrustManager {
        private final X509TrustManager sunJSSEX509TrustManager;

        MyX509TrustManager(String certPath, String certPassword) throws Exception {
            // create a "default" JSSE X509TrustManager.
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(certPath), certPassword.toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
            tmf.init(ks);
            TrustManager[] tms = tmf.getTrustManagers();

            /*
             * Iterate over the returned trustmanagers, look for an instance of
             * X509TrustManager. If found, use that as our "default" trust manager.
             */
            for (TrustManager tm : tms) {
                if (tm instanceof X509TrustManager) {
                    sunJSSEX509TrustManager = (X509TrustManager) tm;
                    return;
                }
            }
            throw new Exception("Couldn't initialize");
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
            } catch (CertificateException excep) {
            }
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException excep) {
            }
        }

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

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值