在Android客户端代码中添加以下内容以发送证书:
KeyStore keyStore = KeyStore.getInstance("PKCS12"); InputStream is = getResources().openRawResource(R.raw.client_cert); keyStore.load(is, "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, "password".toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); InputStream trustStoreStream = getResources().openRawResource(R.raw.client_truststore); KeyStore trustStore = KeyStore.getInstance("BKS"); trustStore.load(trustStoreStream, "password".toCharArray()); tmf.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, tmf.getTrustManagers(), null);
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslContext.getSocketFactory()).build();
Request request = new Request.Builder() .url("https://example.com") .build();
Response response = client.newCall(request).execute(); String result = response.body().string();
其中,client_cert为客户端证书,client_truststore为客户端信任证书库。password为证书和信任证书库的密码。