Java 如何使用证书发出REST Get请求?
我可以使用curl查询get请求:Java 如何使用证书发出REST Get请求?,java,spring,resttemplate,client-certificates,spring-rest,Java,Spring,Resttemplate,Client Certificates,Spring Rest,我可以使用curl查询get请求: curl -k --key some.key --cert some.crt --url "https://app.com:7078/subscribers/checkExists/1" 在那个查询之后,我得到了200ok响应。如何在Java中实现同样的功能?使用Spring RestTemplate 我尝试在internet上禁用手册认证检查: CloseableHttpClient httpClient = HttpClients.custom()
curl -k --key some.key --cert some.crt --url "https://app.com:7078/subscribers/checkExists/1"
在那个查询之后,我得到了200ok
响应。如何在Java中实现同样的功能?使用Spring RestTemplate
我尝试在internet上禁用手册认证检查:
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);
该代码响应我400错误请求
错误
UPD
我还将我的some.crt
文件添加到%JAVA\u HOME%\lib\security
中,并使用命令导入它-keytool-import-alias ca-file some.crt-keystore cacerts-storepass changeit
那么,如何使用
Spring restemplate
在GET
请求中提供some.crt
文件?您需要将密钥添加到Java密钥存储(JKS)中。请参见此处找到的关于使用keytool导入密钥的答案:
您需要将密钥添加到Java密钥库(JKS)。请参见此处找到的关于使用keytool导入密钥的答案:
@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;
}