restTemplate.exchange忽略ssl证书
时间: 2024-03-01 11:30:19 浏览: 157
对于使用 RestTemplate 发起 HTTPS 请求时忽略 SSL 证书验证,你可以通过创建自定义的 HttpClient 来实现。下面是一个示例:
```java
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class SSLIgnoreRestTemplate extends RestTemplate {
public SSLIgnoreRestTemplate() {
super();
initialize();
}
public SSLIgnoreRestTemplate(HttpComponentsClientHttpRequestFactory requestFactory) {
super(requestFactory);
initialize();
}
private void initialize() {
try {
// 创建信任所有证书的 SSLContext
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 null;
}
}}, null);
// 创建忽略 SSL 证书验证的 HttpClient
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier((hostname, session) -> true).build());
setRequestFactory(requestFactory);
} catch (Exception e) {
throw new RuntimeException("Failed to initialize SSLIgnoreRestTemplate", e);
}
}
// 如果有其他需要扩展的方法,可以在这里进行覆盖
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Object... uriVariables) {
return super.execute(url, method, requestCallback, responseExtractor, uriVariables);
}
// ...
}
```
使用时,你可以像使用普通的 RestTemplate 一样进行请求。这个自定义的 RestTemplate 将会忽略 SSL 证书验证。例如:
```java
RestTemplate restTemplate = new SSLIgnoreRestTemplate();
ResponseEntity<String> response = restTemplate.exchange("https://your-url.com", HttpMethod.GET, null, String.class);
```
需要注意的是,忽略 SSL 证书验证存在安全风险,因此建议仅在开发和测试环境中使用,并不推荐在生产环境中使用。
阅读全文