代码架构
文章来源:https://www.toymoban.com/news/detail-472569.html
package com.http.controller;
import com.http.RestTemplateConfig;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping
public class httpControler {
@RequestMapping(value = "two")
public String two() {
RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
String url = "https://www.baidu.com";
ResponseEntity<String> res = restTemplate .getForEntity(url, String.class);
return restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
}
}
package com.http;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
HttpsClientRequestFactory factory = new HttpsClientRequestFactory();
//单位为ms (部分接口数据量大,读取改为60秒)
factory.setReadTimeout(60000);
//单位为ms
factory.setConnectTimeout(10000);
return new RestTemplate(factory);
}
}
package com.http;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.net.HttpURLConnection;
import java.security.KeyStore;
/**
* 继承SimpleClientHttpRequestFactory 根据连接支持实现http和https请求发送
*/
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {
//http协议
super.prepareConnection(connection, httpMethod);
}
if ((connection instanceof HttpsURLConnection)) {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
//https协议
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//信任任何链接(也就是忽略认证)
TrustStrategy anyTrustStrategy = (chain, authType) -> true;
SSLContext ctx = SSLContexts.custom().loadTrustMaterial(trustStore, anyTrustStrategy).build();
httpsURLConnection.setSSLSocketFactory(ctx.getSocketFactory());
super.prepareConnection(httpsURLConnection, httpMethod);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
效果
文章来源地址https://www.toymoban.com/news/detail-472569.html
到了这里,关于restTemplate转发Https请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!