64 lines
2.5 KiB
Java
64 lines
2.5 KiB
Java
package com.designhub.config;
|
||
|
||
import org.springframework.context.annotation.Bean;
|
||
import org.springframework.context.annotation.Configuration;
|
||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||
import org.springframework.web.client.RestTemplate;
|
||
|
||
import javax.net.ssl.*;
|
||
import java.io.IOException;
|
||
import java.net.HttpURLConnection;
|
||
import java.security.KeyManagementException;
|
||
import java.security.NoSuchAlgorithmException;
|
||
import java.security.cert.X509Certificate;
|
||
|
||
/**
|
||
* RestTemplate配置类
|
||
* 支持调用HTTPS接口(信任所有证书)
|
||
*/
|
||
@Configuration
|
||
public class RestTemplateConfig {
|
||
|
||
@Bean
|
||
public RestTemplate restTemplate() throws NoSuchAlgorithmException, KeyManagementException {
|
||
// 创建信任所有证书的 TrustManager
|
||
TrustManager[] trustAllCerts = new TrustManager[]{
|
||
new X509TrustManager() {
|
||
public X509Certificate[] getAcceptedIssuers() { return null; }
|
||
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
|
||
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
|
||
}
|
||
};
|
||
|
||
// 安装信任所有证书的 TrustManager
|
||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
|
||
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
|
||
|
||
// 设置 HostnameVerifier 为信任所有主机名
|
||
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
|
||
|
||
// 创建自定义的 RequestFactory
|
||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() {
|
||
@Override
|
||
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
|
||
if (connection instanceof HttpsURLConnection) {
|
||
((HttpsURLConnection) connection).setHostnameVerifier((hostname, session) -> true);
|
||
try {
|
||
((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
|
||
} catch (Exception e) {
|
||
// ignore
|
||
}
|
||
}
|
||
super.prepareConnection(connection, httpMethod);
|
||
}
|
||
};
|
||
|
||
factory.setConnectTimeout(10000); // 连接超时10秒
|
||
factory.setReadTimeout(30000); // 读取超时30秒
|
||
|
||
return new RestTemplate(factory);
|
||
}
|
||
}
|
||
|