使用restTemplate来访问https

本文介绍如何使用Maven依赖管理和Spring的RestTemplate配置,实现HTTPS接口无证书验证访问。通过自定义SSLContext和SSLConnectionSocketFactory,创建信任所有证书的SSL连接,解决HTTPS请求时的信任问题。

1、maven: <dependency>

        <groupId>org.apache.httpcomponents</groupId>

        <artifactId>httpclient</artifactId>

        <version>4.5.3</version>

      </dependency>

2、@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate() 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;
}
}

测试:

public String getData()
{
//接口地址
String url = "https://free-api.heweather.com/v5/forecast?city=CN101080101&key=5c043b56de9f4371b0c7f8bee8f5b75e";
Map<String, Object> params = new HashMap<>();
params.put("start_time", "20180824");
params.put("end_time", "20180827");
// RestTemplate restTemplate = new RestTemplate();//此处直接autowire即可,不用new
HttpEntity httpEntity = new HttpEntity(params, null);
ResponseEntity<String> request = restTemplate.postForEntity(url, httpEntity, String.class);
return request.getBody().toString();
}

转载于:https://www.cnblogs.com/yuxifly828/p/9857521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值