将服务器端证书和客户端证书保存到本地,客户端证书在D:\download\client.p12,服务器端证书在D:\download\server.cer(本例使用的服务器端证书和客户端证书是使用keytool自创建的,方法见另一篇博客
/console/editor/html/105595647)
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import .ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
public class HttpsDemo {
private final static String PFX_PATH = "D:\\download\\client.p12"; //客户端证书路径
private final static String PFX_PWD = "123456"; //客户端证书密码
public static String sslRequestGet(String url) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
File file = new File(PFX_PATH);
InputStream instream = new FileInputStream(file);
try {
keyStore.load(instream, PFX_PWD.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpGet httpget = new HttpGet(url);
// httpost.addHeader("Connection", "keep-alive");// 设置一些heander等
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");//返回结果
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("java.home"));
String context = sslRequestGet("/");
System.out.println(context);
// System.out.println(sslRequestGet(":443/"));
}
}
在运行前,要先做一些准备工作:
启动服务器端tomcat,打开你需要访问的端口(如: iptables -I INPUT -p tcp --dport 443 -j ACCEPT)
运行,可能会抛出异常
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path
解决方法:
进入 %JAVA_HOME%/jre/lib/security 目录下,运行命令行:
keytool -import -alias server -keystore cacerts -file D:\download\server.cer
回车,输入cacerts证书库的密码:changeit
【查看cacerts证书库:keytool -list -keystore cacerts
删除cacerts证书库中某个证书:keytool -delete -alias akazam_email -keystore cacerts】
重新运行java程序