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();
}
}
}
拿到.pfx证书后如何调用https接口
最新推荐文章于 2024-08-22 13:54:42 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)