欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > SpringBoot 之 配置 RestTemplate + 跳过https 验证

SpringBoot 之 配置 RestTemplate + 跳过https 验证

2024/10/26 7:33:16 来源:https://blog.csdn.net/sszdzq/article/details/142923084  浏览:    关键词:SpringBoot 之 配置 RestTemplate + 跳过https 验证

上截图

目录文件结构

在配置文件下创建下面两个文件

 文件内容

HttpsClientHttpRequestFactory.java

package org.fri.config;import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyStore;/*** 处理无法发送https 请求问题* 忽略 https 校验*/
@Configuration
public class HttpsClientHttpRequestFactory extends SimpleClientHttpRequestFactory {@Overrideprotected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {try {if (connection instanceof HttpsURLConnection) {KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());//信任任何链接,忽略对证书的校验TrustStrategy trustStrategy = (x509Certificates, s) -> true;//自定义sslcontextSSLContext ctx = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();//解决问题((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());//解决No subject alternative names matching IP address xxx.xxx.xxx.xxxx found问题((HttpsURLConnection) connection).setHostnameVerifier((s, sslSession) -> true);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;super.prepareConnection(httpsURLConnection, httpMethod);} else {super.prepareConnection(connection, httpMethod);}} catch (Exception e) {e.printStackTrace();}}
}

 ResTemplateConfig.java

package org.fri.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class ResTemplateConfig {@BeanRestTemplate restTemplate() {return new RestTemplate(new HttpsClientHttpRequestFactory());}
}

配置完成

请求示例

HttpHeaders headers = new HttpHeaders();       
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(reqUri, HttpMethod.GET, requestEntity, JSONObject.class);
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {log.info(responseEntity.getBody().toJSONString());
}

 完结撒花!!!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com