依赖
java
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
code
java
package com.hexin.cbas.test;
import org.apache.commons.net.util.TrustManagerUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;
public class Https2Test {
private final static String PFX_PATH = "D:\\person_client.p12";
private final static String PFX_PWD = "pwd"; //客户端证书密码及密钥库密码
public static String sslRequestGet(String url) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream stream = Files.newInputStream(Paths.get(PFX_PATH))){
// 这里就指的是KeyStore库的密码
keyStore.load(stream, PFX_PWD.toCharArray());
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, PFX_PWD.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager[] {TrustManagerUtils.getAcceptAllTrustManager()};
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, null);
HttpGet httpget = new HttpGet(url);
try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
CloseableHttpResponse response = httpclient.execute(httpget)){
// 返回结果
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
}
public static void main(String[] args) throws Exception {
//url使用的是域名是需要设置,否则会报handshake alert: unrecognized_name错误
System.setProperty("jsse.enableSNIExtension", "false");
System.out.println(sslRequestGet("https://xxxxx.com/user/get"));
}
}