有没有人有关于如何使用 HTTPClient 4.0.1 通过 x509 证书执行客户端身份验证的任何友好提示?
最佳答案
这里有一些代码可以让你开始。 KeyStore
是包含客户端证书的对象。如果服务器使用的是自签名证书或未经 JVM 在包含的 cacerts 文件中识别的 CA 签名的证书,则您将需要使用 TrustStore
。否则要使用默认的 cacerts 文件,将 null
传递给 SSLSockeFactory
作为信任库参数..
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 pkcs12
final KeyStore keystore = KeyStore.getInstance("pkcs12");
InputStream keystoreInput = null;
// TODO get the keystore as an InputStream from somewhere
keystore.load(keystoreInput, "keystorepassword".toCharArray());
// load the trustore, leave it null to rely on cacerts distributed with the JVM - truststore type is probably jks or pkcs12
KeyStore truststore = KeyStore.getInstance("pkcs12");
InputStream truststoreInput = null;
// TODO get the trustore as an InputStream from somewhere
truststore.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);
关于java - 使用 HttpClient 4.0.1 使用 x509 证书进行相互身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375121/