resttemplate 无视ssl证书
时间: 2023-09-26 14:06:05 浏览: 172
要使RestTemplate忽略SSL证书,你可以创建一个自定义的SimpleClientHttpRequestFactory,并覆盖其createRequest方法。在这个方法中,你可以使用自定义的SSLContext和HostnameVerifier来创建HttpsURLConnection,并绕过证书验证。以下是一个示例代码:
```java
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class SSL extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
// Create a custom SSLContext that trusts all certificates
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() { return null; }
}}, null);
} catch (Exception e) {
throw new IOException("Failed to create SSLContext", e);
}
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
((HttpsURLConnection) connection).setSSLSocketFactory(socketFactory);
// Bypass hostname verification
((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
super.prepareConnection(connection, httpMethod);
}
}
// 使用自定义的SSL类创建RestTemplate
RestTemplate restTemplate = new RestTemplate(new SSL());
// 现在,你可以使用这个RestTemplate进行无视SSL证书的请求了
```
通过使用这个自定义的SSL类创建RestTemplate,你可以使其忽略SSL证书验证,并且可以安全地发送请求。请注意,这样做会增加潜在的安全风险,因为它不验证服务器的身份。所以在生产环境中使用时需谨慎。
阅读全文