我想使用 RestTemplate 发送带有 SSL 证书的请求。为了生成 RestTemplate,我创建了下面的函数。
protected RestTemplate createRestTemplate2(){
KeyStore clientStore = KeyStore.getInstance("PKCS12");
FileInputStream keyStoreFile = new FileInputStream("certifacate_file.p12");
char[] keyStorePassword = "password".toCharArray();
clientStore.load(keyStoreFile, keyStorePassword)
SSLContext sslContext = SSLContextBuilder.create()
.setProtocol("TLS")
.loadKeyMaterial(clientStore, keyStorePassword)
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).build();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // Error happens at here
return new RestTemplate(requestFactory);
}
但是当我运行它时,我收到以下错误。
Could not find matching constructor for: org.springframework.http.client.HttpComponentsClientHttpRequestFactory(org.apache.hc.client5.http.impl.classic.InternalHttpClient)
在我的项目中,我使用 Apache HttpClient 5.x,但问题是
new HttpComponentsClientHttpRequestFactory()
不使用相同的版本,因此我收到此错误。但问题是互联网上的所有指南都表明可以这样做,但我无法做到。你能帮我吗?
这并不能回答您的确切问题(有必要知道您使用的 Spring Framework 和 Apache HttpClient 的版本来执行此操作),但如果您使用的是 Spring Boot 3.1 或更高版本,则不需要执行此设置手动,因为 Spring Boot 可以为您配置
RestTemplate
SSL 连接。
首先,从证书创建 SSL 捆绑包:
spring:
ssl:
bundle:
jks:
client:
key:
alias: "myalias"
truststore:
location: "classpath:certifacate_file.p12"
password: "password"
type: "PKCS12"
然后 使用 SSL 捆绑包创建
RestTemplate
:
protected RestTemplate createRestTemplate2(RestTemplateBuilder builder, SslBundles sslBundles) {
return restTemplateBuilder.setSslBundle(sslBundles.getBundle("client")).build();
}