方法一:程式設計方式配置SSLContext與TrustManager
// 載入PKCS12格式的客戶端證書和私鑰 KeyStore keyStore = KeyStore.getInstance("PKCS12"); char[] keystorePassword = "your Certificate Passphrase".toCharArray(); String clientKeyPath = ResourceUtils.getFile("classpath:security/ctt.p12").getAbsolutePath(); FileInputStream fis = new FileInputStream(clientKeyPath); try { keyStore.load(fis, keystorePassword); } finally { fis.close(); } // 初始化KeyManagerFactory String algorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(keyStore, keystorePassword); // 建立TrustManagerFactory,這裡假設我們信任伺服器提供的證書 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); // 建立SSLContext並設定KeyManager和TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); String result = HttpRequest.post(schedulingConfigProperties.getTokenUrl()) .header(HttpHeaders.CONNECTION, "keep-alive") .setSSLSocketFactory(sslContext.getSocketFactory()) .timeout(20000)//超時,毫秒 .form(paramMap) .addRequestInterceptor(request -> { }) .execute().body();
//然後在http client或者webservice client設定對應的客戶端代理類中
String result = HttpRequest.post(schedulingConfigProperties.getTokenUrl())
.header(HttpHeaders.CONNECTION, "keep-alive")
.setSSLSocketFactory(sslContext.getSocketFactory())
.timeout(20000)
.form(paramMap)
.addRequestInterceptor(request -> {
})
.execute().body();