gpt4 book ai didi

java - 如何使用证书发出 REST Get 请求?

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:56 24 4
gpt4 key购买 nike

我可以使用curl查询get请求:

curl -k --key some.key --cert some.crt --url "https://app.com:7078/subscribers/checkExists/1"

在该查询之后,我得到 200 OK 响应。我怎样才能在Java中达到同样的效果?使用Spring RestTemplate?

我尝试通过互联网中的手册禁用认证检查:

CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

ResponseEntity<String> response = null;
String urlOverHttps = "https://app.com:7078/subscribers/checkExists/1";
response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);

我也通过@Configuration尝试过:

@Bean
public boolean disableSSLValidation() throws Exception {
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}

@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, null);

HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return true;
}

该代码响应我的 400 Bad Request 错误。

UPD

我还将我的 some.crt 文件添加到 %JAVA_HOME%\lib\security 并使用命令导入它 - keytool -import -alias ca -file some.crt -keystore cacerts -storepass changeit

那么,如何使用 Spring RestTemplateGET 请求中提供我的 some.crt 文件?

最佳答案

您需要将 key 添加到 Java key 存储 (JKS)。请参阅此处找到的有关使用 keytool 导入 key 的答案:

How to import an existing x509 certificate and private key in Java keystore to use in SSL?

关于java - 如何使用证书发出 REST Get 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007757/

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