对安全性有要求的网站一般使用https来加密传输的请求和响应。https离不开证书,关于证书不在多说。Apache的HttpClient支持https,
下面是官方的样例程序,程序中使用了my.store这个文件,
这个文件不是网站的证书,而是一份包含自己密码的自己的证书库。这个文件是需要自己生成的,使用jdk中的keytool命令可以很方便的生成my.store文件。步骤如下(以支付宝为例):
浏览器(以chrome为例)访问https://www.alipay.com/,点击域名左侧的小锁,可以查看支付宝的证书信息
将支付包的证书信息导出,证书格式有很多中,der、cer等。随便选择即可。
命令行或者shell执行 keytool -import -alias "my alipay cert" -file www.alipay.com.cert -keystore my.store,
如果keytool命令不识别,去检查一下jdk的环境变量是否设置正确。”my alipay cert”是个别名,随便取。“www.alipay.com.cert”这个文件就是从浏览器中导出的支付宝的证书。
“my.store”是生成的自己 的证书库文件。回车执行,效果如下:
OK,现在可以执行下面的代码了:
package com.yeetrack.httpclient;
/**
* Created with IntelliJ IDEA.
* User: victor
* Date: 13-10-11
* Time: 下午3:09
* To change this template use File | Settings | File Templates.
*/
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.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.SSLContexts;
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.util.EntityUtils;
/**
* 代码展示了如果使用ssl context创建安全socket连接
*/
public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//加载证书文件
FileInputStream instream = new FileInputStream(new File("/home/victor/my.store"));
try {
trustStore.load(instream, "mypassword".toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try
{
//访问支付宝
HttpGet httpget = new HttpGet("https://www.alipay.com/");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}