代码架构
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();
}
}
}
效果