RestTemplate调用https服务的时候,由于服务方的ssl证书并非正式证书,不被jdk继承,故会报雷同:“No subject alternative names matching IP address xxxxxx found”的错误。网上找了一下,处置处罚也比力简朴,基本上是配置下:HttpRequestFactory。但找到的内容很多都是需要注入bean,通过@Config等方式配置,这样的话,不是很便利。
以下代码,通过直接调用main函数,处置处罚了RestTemplate,使其忽略SSL证书。
- 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.http.HttpHeaders;
- 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;
- public class TestNoSSLRest {
- static String URL = "https://192.168.88.70:8443/oauth/oauth2/token?grant_type=authorization_code&code=iDCQAU";
- public static void main(String[] args) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
- RestTemplate restTemplate = new RestTemplate(generateHttpRequestFactory());
- String responseStr = restTemplate.postForObject(URL, initHttpHeaders(), String.class);
- System.out.println(responseStr);
- }
- private static HttpHeaders initHttpHeaders() {
- HttpHeaders headers = new HttpHeaders();
- headers.add("Authorization", "Basic Soiuawe12asildfSEjasdfewe22");
- return headers;
- }
- private static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
- TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
- SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
- SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
- HttpClientBuilder httpClientBuilder = HttpClients.custom();
- httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
- CloseableHttpClient httpClient = httpClientBuilder.build();
- HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
- factory.setHttpClient(httpClient);
- return factory;
- }
- }
复制代码 其中,该class依赖的jar包为:
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.5.10</version>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpcore</artifactId>
- <version>4.4.15</version>
- </dependency>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |