gpt4 book ai didi

java - 在 Java HTTP 请求中包含 .pem 证书

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:35 26 4
gpt4 key购买 nike

我目前能够使用以下 curl 命令访问需要客户端证书的 Web 服务:

curl -k -v --cert ./certificate.pem https://api.com/unit

如何在 Java 应用程序中发出此请求?

请注意,我需要 -k 标志,它允许 curl 建立“不安全”的 SSL 连接。这也需要在 Java 应用程序中完成。

最佳答案

下面的代码提供了一个“sendSSLRequest”方法,它发送带有客户端 SSL 身份验证的 HTTP GET 请求。

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpGet;

public class SSLExample {

private final static String ENDPOINT_URL = "https://api.com/unit";

public void sendSSLRequest() {

final SSLContext sslContext = SSLContextLoader.initSSLContext();

final HttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.build();
final HttpGet request = new HttpGet(ENDPOINT_URL);

try {
client.execute(request);
} catch (final IOException e) {
//do some exception handling...
}
}
}

现在,SSLContext:您需要在某处对其进行初始化。下面的“initSSLContext”方法将从给定的 keystore 加载 key Material ,并从给定的信任库加载信任 Material (要信任的证书)。

public class SSLContextLoader {

private final static String clientKeyStorePath = "/path/to/client/keystore";
private final static String trustStorePath = "/path/to/truststore";
private final static String clientKeyStorePassword = "/password/for/client/keystore";
private final static String trustStorePassword = "/password/for/truststore";
private final static String keyPassword = "/passphrase/for/private/key";

public static SSLContext initSSLContext () {
try {
final KeyStore clientKeystore = KeyStore.getInstance("JKS");
clientKeystore.load(new FileInputStream(clientKeyStorePath), clientKeyStorePassword.toCharArray());
final KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());

final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(trustStore, null)
.loadKeyMaterial(clientKeystore, keyPassword.toCharArray())
.build();

return sslContext;
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
}

关于 -k 选项,我邀请您查看以下问题/答案:Trusting all certificates using HttpClient over HTTPS .

关于java - 在 Java HTTP 请求中包含 .pem 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47161402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com