RestTemplate 发送https请求
程序员文章站
2022-06-25 20:17:43
...
maven依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
/**
* @Description restTemplate 配置类
* @since
*/
@Configuration
public class RestTemplateConfig {
@Bean(name = "httpsRestTemplate")
public RestTemplate getHttpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
}
推荐阅读
-
windows下通过证书的方式进行curl请求https链接失败,怎么办
-
解决file_get_contents无法请求https连接的方法_PHP教程
-
curl如何通过代理IP请求https网址
-
如何设置Fiddler来拦截Java代码发送的HTTP请求,进行各种问题排查
-
PHP + Socket 发送http请求进而实现网站灌水
-
Node.js发送HTTP客户端请求并显示响应结果的方法示例
-
客户端socket发送http POST请求可以触发服务端PHP页面的isset吗?解决思路
-
php模拟post请求发送文件
-
如何用原生JS实现并行发送AJAX请求?
-
php在一个请求中,发送另一个请求