使用,只需要按照下面的模板,传递参数即可
这次给大家带来的是RestTemplate请求https接口,我们都知道,https接口一般是需要证书才能访问的,但是我们可以采取一些特殊的手段,跳过证书验证。下面,老哥讲下具体的代码
配置一个RestTemplate的bean,说明:RestTemplate是spring-web自带的,我们不需要额外引入什么包
@Configuration
public class RestTemplateConfig {
/**
* 构建支持忽略自签名证书的Restemplate的bean
* @return 支持发起https请求的RestTemplate对象
* @throws KeyStoreException 证书异常
* @throws NoSuchAlgorithmException 加密算法不可用异常
* @throws KeyManagementException 密钥管理异常
*/
@Bean("httpsTemplate")
public RestTemplate createHttpsRestTemplate()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(
sslContext, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslFactory)
.build();
HttpComponentsClientHttpRequestFactory factory =
new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(3600000);
factory.setReadTimeout(3600000);
factory.setHttpClient(httpClient);
return new RestTemplate(factory);
}
}
文章为作者独立观点,不代表股票交易接口观点