其他答案显示了如何全局配置客户端证书。但是,如果您希望以编程方式为一个特定连接定义客户端密钥,而不是在JVM上运行的每个应用程序中全局定义它,那么您可以配置您自己的SSLContext,如下所示:
String keyPassphrase = "";
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("cert-key-pair.pfx"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, null)
.build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet("https://example.com"));