一、创建UcRESTTemplate管理器封装
import com.alibaba.fastjson.JSON;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.Map;
所需导入的包
public class UcRESTTemplate { private static final int default_connectionTimeout = 30 * 1000;
private static final int default_socketTimeout = 30 * 1000;
private int connectionTimeout = 30 * 1000;
private int socketTimeout = 30 * 1000;
private int minsTimeoutTime = 1000; private static final Logger logger = LoggerFactory.getLogger(UcRESTTemplate.class); public UcRESTTemplate() {
this.connectionTimeout = UcRESTTemplate.default_connectionTimeout;
this.socketTimeout = UcRESTTemplate.default_socketTimeout;
} public UcRESTTemplate(int connectionTimeout, int socketTimeout) {
this.connectionTimeout = connectionTimeout < this.minsTimeoutTime ? UcRESTTemplate.default_connectionTimeout
: connectionTimeout;
this.socketTimeout = socketTimeout < this.minsTimeoutTime ? UcRESTTemplate.default_socketTimeout
: socketTimeout;
} private CloseableHttpClient buildHttpClient() {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connectionTimeout)
.setSocketTimeout(this.socketTimeout).build();
HttpClientBuilder cb = HttpClients
.custom()
.disableAutomaticRetries()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setDefaultRequestConfig(requestConfig); try {
// set ssl context
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { new X509TrustManager() { @Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
} @Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
} @Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
}
} }, null); cb.setSslcontext(ctx);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
return cb.build();
} private static RestTemplate buildTemplate(CloseableHttpClient client) {
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
client);
return new RestTemplate(requestFactory);
} /**
* @param request
* @param url
* @param params maybe null
* @return
*/
public ResponseEntity<String> getEntity(String url, HttpEntity<?> request, Map<String, ?> params) {
if (null == params){
return getEntity(url, request, String.class);
}else {
try {
try (CloseableHttpClient client = this.buildHttpClient();) {
return UcRESTTemplate.buildTemplate(client).exchange(url, HttpMethod.GET, request, String.class, params);
} catch (HttpStatusCodeException ex) {
this.handleServerException(url, ex);
return null;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} public ResponseEntity<String> getEntity(String url, HttpEntity<?> request) {
return getEntity(url, request, String.class);
} public <T> ResponseEntity<T> getEntity(String url, HttpEntity<?> request, Class<T> responseType) {
try {
try (CloseableHttpClient client = this.buildHttpClient();) {
return UcRESTTemplate.buildTemplate(client).exchange(url, HttpMethod.GET, request, responseType);
} catch (HttpStatusCodeException ex) {
this.handleServerException(url, ex);
return null;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} public ResponseEntity<String> postEntity(String url, HttpEntity<?> request) {
try {
try (CloseableHttpClient client = this.buildHttpClient();) {
return UcRESTTemplate.buildTemplate(client).postForEntity(url, request,
String.class);
} catch (HttpStatusCodeException ex) {
return this.handleServerException(url, ex);
}
} catch (IOException e) {
UcRESTTemplate.logger.error("exception is " + e);
throw new RuntimeException(e);
}
} protected ResponseEntity<String> handleServerException(String url,
HttpStatusCodeException ex) {
HttpStatus statusCode = ex.getStatusCode();
String respString = ex.getResponseBodyAsString();
logger.error("url:" + url+",statusCode:"+statusCode, ex);
switch (statusCode) {
case CONFLICT:
return new ResponseEntity<>(respString, statusCode);
case NOT_FOUND:
throw new RuntimeException("URL not found: " + url);
default:
logger.error("Response string:\n" + respString);
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) JSON.parse(respString);
if (map.containsKey("stackTrace")) {
Exception ori = JSON.parseObject(respString, Exception.class);
throw new RuntimeException("Exception thrown from server", ori);
} else {
throw new RuntimeException(respString);
}
}
} /**
* 发送get请求,获取返回结果
*
* @param <T>
* @param url
* @param cls
* @return
*/
public <T> T sendHttpsGet(String url, Class<T> cls) {
CloseableHttpClient client = this.buildHttpClient();
return buildTemplate(client).getForObject(url, cls);
} }