問題描述
使用RestTemplate發(fā)送HTTPS請求的時(shí)候,出現(xiàn)了這樣的一個(gè)問題:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
RestTemplate 默認(rèn)不支持https協(xié)議
解決方案:
????????第一種是忽略認(rèn)證
????????第二種是導(dǎo)入證書,比較復(fù)雜(比第一種安全)?
解決方案:
這里說一下第一種解決方案,忽略認(rèn)證
版本:Spring Boot2.x
RestTemplateConfig
package com.test.config;
import java.nio.charset.Charset;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig{
@Bean("restTemplate")
public RestTemplate RestTemplate() {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(30000);
httpRequestFactory.setConnectTimeout(30000);
httpRequestFactory.setReadTimeout(30000);
return new RestTemplate(httpRequestFactory);
}
/**
* 用于https請求,忽略認(rèn)證
* @return unSSLRestTemplate
*/
@Bean("unSSLRestTemplate")
public RestTemplate restTemplateHttps() {
RestTemplate restTemplate = null;
try {
TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
HttpClientBuilder clientBuilder = HttpClients.custom();
CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(30000);
httpRequestFactory.setConnectTimeout(30000);
httpRequestFactory.setReadTimeout(30000);
httpRequestFactory.setHttpClient(httpClient);
restTemplate = new RestTemplate(httpRequestFactory);
//解決亂碼
List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
httpMessageConverters.stream().forEach(httpMessageConverter ->{
if(httpMessageConverter instanceof StringHttpMessageConverter){
StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
}
});
} catch (Exception e) {
e.printStackTrace();
}
return restTemplate;
}
}
測試代碼
package com.test.service;
import javax.annotation.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* http請求&https請求
*/
@Service
public class TestService {
//http請求
@Resource(name = "restTemplate")
private RestTemplate restTemplate;
//https請求
@Resource(name = "unSSLRestTemplate")
private RestTemplate unSSLRestTemplate;
/**
* http請求
*/
public void interfaceHttp(JSONObject params) {
//參數(shù)
String json = params.toJSONString();
//請求頭
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
restTemplate.postForObject(URL, formEntity, String.class);
}
/**
* https請求
*/
public void interfaceHttps(JSONObject params) {
//參數(shù)
String json = params.toJSONString();
//請求頭
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
unSSLRestTemplate.postForObject(URL, formEntity, String.class);
}
}
說明:這里兼容http和https請求,只需要指定名稱即可?
更新:Spring Boot3.x依賴包不一樣
版本:Spring Boot3.x
加上maven依賴文章來源:http://www.zghlxwxcb.cn/news/detail-693069.html
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
?RestTemplateConfig文章來源地址http://www.zghlxwxcb.cn/news/detail-693069.html
package com.test.config;
import java.nio.charset.Charset;
import java.util.List;
import javax.net.ssl.SSLContext;
//這里引用client5的包
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig{
@Bean("restTemplate")
public RestTemplate RestTemplate() {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(30000);
httpRequestFactory.setConnectTimeout(30000);
httpRequestFactory.setReadTimeout(30000);
return new RestTemplate(httpRequestFactory);
}
/**
* 用于https請求,忽略認(rèn)證
* @return unSSLRestTemplate
*/
@Bean("unSSLRestTemplate")
public RestTemplate restTemplateHttps() {
RestTemplate restTemplate = null;
try {
TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
HttpClientBuilder clientBuilder = HttpClients.custom();
//調(diào)整了這里
CloseableHttpClient httpClient = clientBuilder.setConnectionManager(PoolingHttpClientConnectionManagerBuilder
.create().setSSLSocketFactory(sslsf).build()).build();
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(30000);
httpRequestFactory.setConnectTimeout(30000);
httpRequestFactory.setReadTimeout(30000);
httpRequestFactory.setHttpClient(httpClient);
restTemplate = new RestTemplate(httpRequestFactory);
//解決亂碼
List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
httpMessageConverters.stream().forEach(httpMessageConverter ->{
if(httpMessageConverter instanceof StringHttpMessageConverter){
StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
}
});
} catch (Exception e) {
e.printStackTrace();
}
return restTemplate;
}
}
到了這里,關(guān)于RestTemplate HTTPS請求忽略SSL證書的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!