spring RestTemplateUtils 工具类
V2.0 版本(优化部分代码)
可绕过https请求,带异常处理,容错机制,以及设置链接时间.设置读写时间。
工具类可以 http请求 https 请求
支持 post,get,加密,请求方式
工具类
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* Created by huangquanwei on 2019/5/31 15:58
* restTemplateUtils 高性能请求http https
* 时间单位 毫秒
*/
@Slf4j
public class RestTemplateUtils {
// 默认时间五秒,不重试。
private final static int CONNEC_TIMEOUT = 5000;
private final static int READ_TIMEOUT = 5000;
private final static int RETRY_COUNT = 1;
/**
* https 请求 GET
* @param url 地址
* @param connecTimeout 连接时间 毫秒
* @param readTimeout 读取时间 毫秒
* @param retryCount 重试机制
* @return String 类型
*/
public static String getHttp(String url, int connecTimeout, int readTimeout, int retryCount) {
RestTemplate restTemplate = simpeClient(url, connecTimeout, readTimeout);
String result = null; // 返回值类型;
for (int i = 1; i <= retryCount; i++) {
try {
result = restTemplate.getForObject(url, String.class);
return result;
} catch (RestClientException e) {
log.error("-----------开始-----------重试count: " + i);
e.printStackTrace();
}
}
return null;
}
/**
* https 请求 GET
* @param url 地址
* @return String 类型
*/
public static String getHttp(String url) {
RestTemplate restTemplate = simpeClient(url, CONNEC_TIMEOUT, READ_TIMEOUT);
String result = null; // 返回值类型;
for (int i = 1; i <= RETRY_COUNT; i++) {
try {
result = restTemplate.getForObject(url, String.class);
return result;
} catch (RestClientException e) {
log.error("-----------开始-----------重试count: " + i);
e.printStackTrace();
}
}
return null;
}
/**
* http 请求 post
* @param url 地址
* @param params 参数
* @param headersMap header
* @param connecTimeout 连接时间
* @param readTimeout 读取时间`
* @param retryCount 重试机制
* @return String 类型
*/
public static String postHttp(String url, JSONObject params, Map headersMap, int connecTimeout, int readTimeout, int retryCount) {
RestTemplate restTemplate = simpeClient(url, connecTimeout, readTimeout);
// 设置·header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAll(headersMap);
HttpEntity requestEntity = new HttpEntity(params, requestHeaders); // josn utf-8 格式
String result = null; // 返回值类型;
for (int i = 1; i <= retryCount; i++) {
try {
result = restTemplate.postForObject(url, requestEntity, String.class);
return result;
} catch (RestClientException e) {
log.error("-----------开始-----------重试count: " + i);
e.printStackTrace();
}
}
return null;
}
/**
* http 请求 post
* @param url 地址
* @param params 参数
* @param headersMap header
* @return String 类型
*/
public static String postHttp(String url, JSONObject params, Map headersMap) {
RestTemplate restTemplate = simpeClient(url, CONNEC_TIMEOUT, READ_TIMEOUT);
// 设置·header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAll(headersMap);
HttpEntity requestEntity = new HttpEntity(params, requestHeaders); // josn utf-8 格式
String result = null; // 返回值类型;
for (int i = 1; i <= RETRY_COUNT; i++) {
try {
result = restTemplate.postForObject(url, requestEntity, String.class);
return result;
} catch (RestClientException e) {
log.error("-----------开始-----------重试count: " + i);
e.printStackTrace();
}
}
return null;
}
/**
* 加密参数类型请求 application/x-www-form-urlencoded
* MultiValueMap
* 采用 HttpEntity> 构造
* http 请求 post
*
* @param url 地址
* @param postParameters 参数
* @param headersMap header
* @param connecTimeout 连接时间
* @param readTimeout 读取时间
* @param retryCount 重试机制
* @return String 类型
*/
public static String postHttpEncryption(String url, MultiValueMap postParameters, Map headersMap, int connecTimeout, int readTimeout, int retryCount) {
RestTemplate restTemplate = simpeClient(url, connecTimeout, readTimeout);
// 设置·header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAll(headersMap);
HttpEntity> requestEntity = new HttpEntity<>(postParameters, requestHeaders);
String result = null; // 返回值类型;
for (int i = 1; i <= retryCount; i++) {
try {
result = restTemplate.postForObject(url, requestEntity, String.class);
return result;
} catch (RestClientException e) {
log.error("-----------开始-----------重试count: " + i);
e.printStackTrace();
}
}
return null;
}
/**
* 加密参数类型请求 application/x-www-form-urlencoded
* MultiValueMap
* 采用 HttpEntity> 构造
* http 请求 post
* @param url 地址
* @param postParameters 参数
* @param headersMap header
* @return String 类型
*/
public static String postHttpEncryption(String url, MultiValueMap postParameters, Map headersMap) {
RestTemplate restTemplate = simpeClient(url, CONNEC_TIMEOUT, READ_TIMEOUT);
// 设置·header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAll(headersMap);
HttpEntity> requestEntity = new HttpEntity<>(postParameters, requestHeaders);
String result = null; // 返回值类型;
for (int i = 1; i <= RETRY_COUNT; i++) {
try {
result = restTemplate.postForObject(url, requestEntity, String.class);
return result;
} catch (RestClientException e) {
log.error("-----------开始-----------重试count: " + i);
e.printStackTrace();
}
}
return null;
}
private static RestTemplate simpeClient(String url, int connecTimeout, int readTimeout) {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(connecTimeout);
requestFactory.setReadTimeout(readTimeout);
RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); //error处理
if (url.contains("https")){
restTemplate.setRequestFactory(new HttpsClientRequestFactory()); // 绕过https
}
return restTemplate;
}
/**
* @ClassName: DefaultResponseErrorHandler
* @Description: TODO
* @author:
* @date: 2
*/
private static class DefaultResponseErrorHandler implements ResponseErrorHandler {
/**
* 对response进行判断,如果是异常情况,返回true
*/
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().value() != HttpServletResponse.SC_OK;
}
/**
* 异常情况时的处理方法
*/
@Override
public void handleError(ClientHttpResponse response) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
StringBuilder sb = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str);
}
try {
throw new Exception(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.X509Certificate;
/**
* Created by huangquanwei on 2019/6/1 10:30
* Https 绕过
*/
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
* see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
*/
// SSLSocketFactory用于创建 SSLSockets
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
// 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
// 这些默认的服务的最低质量要求保密保护和服务器身份验证
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
// 返回的密码套件可用于SSL连接启用的名字
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port,
final boolean autoClose) throws IOException {
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
private Socket overrideProtocol(final Socket socket) {
if (!(socket instanceof SSLSocket)) {
throw new RuntimeException("An instance of SSLSocket is expected");
}
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
return socket;
}
}
}
如果合适你的项目,请点赞哦!