看这篇内容时,我相信你已经看完了关于这部分的前三篇文章:HttpClient访问https链接(一)HttpClient访问https链接(二)HTTPCLIENT访问HTTPS链接(三、配置TOMCAT7的SSL)。这篇的内容会接着前三篇的内容继续,重复的那部分代码就不会再处理。

有了前面介绍的内容,这次的内容就变得很简单。

首先,我们需要按照HTTPCLIENT访问HTTPS链接(三、配置TOMCAT7的SSL)中的方法,创建客户端证书,同时按照HttpClient访问https链接(二)中的方法,把客户端证书制作成为bks格式的证书。
通过构造方法SSLSocketFactory(KeyStore keystore, String keystorePassword, KeyStore truststore)指定服务端证书,客户端证书。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* 获取本地KeyStore(Client)
*
* @param mContext
* @return
*/
private static KeyStore getKeyStore(Context mContext, String passwd) {
AssetManager am = mContext.getAssets();
InputStream ins = null;
try {
ins = am.open("client.bks");
// 创建一个证书库,并将证书导入证书库
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(ins, passwd.toCharArray());
return keyStore;
} catch (Exception e) {
try {
return KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e1) {
return null;
}
} finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
}
}
}
}

/**
* 获取信任的KeyStore(服务端)
*
* @param mContext
* @return
*/
private static KeyStore getTrustKeyStore(Context mContext) {
AssetManager am = mContext.getAssets();
InputStream ins = null;
try {
ins = am.open("server.cer");
// 读取证书
CertificateFactory cerFactory = CertificateFactory
.getInstance("X.509"); //
Certificate cer = cerFactory.generateCertificate(ins);
// 创建一个证书库,并将证书导入证书库
KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
keyStore.load(null, null);
keyStore.setCertificateEntry("trust", cer);
return keyStore;
} catch (Exception e) {
try {
return KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e1) {
return null;
}
} finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
}
}
}
}

/**
* 获取支持HTTPS的HttpClient
*
* @return
*/
public static DefaultHttpClient getNewHttpClient3(Context mContext) {
try {
KeyStore trustStore = null;
KeyStore store = null;
SSLSocketFactory sf = null;
trustStore = getTrustKeyStore(mContext);
store = getKeyStore(mContext, "123456");
// trustStore.load(null, null);
sf = new SSLSocketFactory(store, "123456", trustStore);
// sf = new SSLSocketFactory(trustStore);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}