开发过程用到的,特此记录
import com.alibaba.fastjson.JSON;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
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;
public class HttpsRequestTest {
// 要访问的url
private static final String URL = "https://esation";
// 证书路径
private static final String CERT_PATH = "C:\\Users\\282\\Desktop\\Test.pfx";
// 证书密码
private static final String CERT_PASSWORD = "password";
private SSLSocketFactory sslFactory = null;
public static void main(String[] args) {
HttpsRequestTest test = new HttpsRequestTest();
Object requestBody = new Object();
String result = test.httpsRequest(requestBody);
System.out.println(result);
}
public String httpsRequest(Object requestBody) {
try {
Map<String, String> headers = new HashMap<>(2);
headers.put("Content-Type", "application/json");
HttpURLConnection connection = doHttpRequest(URL, "POST", 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 HttpURLConnection doHttpRequest(String requestUrl, String method, Object req, Map<String, String> header) throws Exception {
HttpURLConnection conn;
String body = JSON.toJSONString(req);
if (method == null || method.length() == 0) {
method = "GET";
}
if ("GET".equals(method) && !body.isEmpty()) {
requestUrl = requestUrl + "?" + body;
}
URL url = new URL(requestUrl);
conn = (HttpURLConnection) 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(CERT_PATH, CERT_PASSWORD));
}
if (header != null) {
for (String key : header.keySet()) {
conn.setRequestProperty(key, header.get(key));
}
}
if (!body.isEmpty()) {
if (!"GET".equals(method)) {
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(body);
wr.close();
}
}
conn.connect();
return conn;
}
private static int getResponseCode(HttpURLConnection connection) throws IOException {
return connection.getResponseCode();
}
private static String getResponseBodyAsString(HttpURLConnection 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();
}
}
}
maven
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>