0
我安装了证书(用户),我需要使用它来连接服务器。我是否需要做更多的事情才能将其用于安全连接?Android - 安装证书,但如何使用它来连接?
我安装了证书(用户),我需要使用它来连接服务器。我是否需要做更多的事情才能将其用于安全连接?Android - 安装证书,但如何使用它来连接?
通过将证书复制到应用程序专用存储器来导入证书。
设置包含证书的自定义KeyStore,然后使用它创建自定义SSLContext。
一旦我们引用了包含证书的客户端证书和密码的文件,我们就会将其加载到适当的KeyStore中。
keyStore = KeyStore.getInstance("PKCS12");
fis = new FileInputStream(certificateFile);<br>keyStore.load(fis, clientCertPassword.toCharArray());
现在我们有一个包含客户端证书的密钥库,我们可以用它来构建的SSLContext:
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, clientCertPassword.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, null, null);
的的SSLContext然后可以用一个HttpURLConnection类用于连接到服务器:
String result = null;
HttpURLConnection urlConnection = null;
try {
URL requestedUrl = new URL(url);
urlConnection = (HttpURLConnection) requestedUrl.openConnection();
if(urlConnection instanceof HttpsURLConnection) {
((HttpsURLConnection)urlConnection)
.setSSLSocketFactory(sslContext.getSocketFactory());
}
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(1500);
urlConnection.setReadTimeout(1500);
lastResponseCode = urlConnection.getResponseCode();
result = IOUtil.readFully(urlConnection.getInputStream());
lastContentType = urlConnection.getContentType();
} catch(Exception ex) {
result = ex.toString();
} finally {
if(urlConnection != null) {
urlConnection.disconnect();
}
}
http://chariotsolutions.com/blog/post/https-with-client-certificates-on/