这是一些代码,助您一臂之力。该
KeyStore是包含客户端证书的对象。如果服务器使用的是自签名证书,或者包含的cacerts文件中的JVM认可的不是CA所签名的证书,则需要使用
TrustStore。否则,要使用默认的cacerts文件,请传递
null给
SSLSockeFactorytruststore参数。
import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeRegistry;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpParams;...final HttpParams httpParams = new BasicHttpParams();// load the keystore containing the client certificate - keystore type is probably jks or pkcs12final KeyStore keystore = KeyStore.getInstance("pkcs12");InputStream keystoreInput = null;// TODO get the keystore as an InputStream from somewherekeystore.load(keystoreInput, "keystorepassword".toCharArray());// load the trustore, leave it null to rely on cacerts distributed with the JVM - truststore type is probably jks or pkcs12KeyStore truststore = KeyStore.getInstance("pkcs12");InputStream truststoreInput = null;// TODO get the trustore as an InputStream from somewheretruststore.load(truststoreInput, "truststorepassword".toCharArray());final SchemeRegistry schemeRegistry = new SchemeRegistry();schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keystore, keystorePassword, truststore), 443));final DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);


