相关依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.8</version>
</dependency>
RestTemplateConfig
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectionRequestTimeout(60000);
factory.setReadTimeout(30000);
return factory;
}
public static HttpComponentsClientHttpRequestFactory createHttpRequestFactory()
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
return factory;
}
public static RestTemplate getHttpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
}
/**
* <p>
* http工具类
* </p>
*
* @author xzc
* @since 2021-12-24
*/
@Slf4j
public class JlHttp {
// 请求的默认信息头
private HttpHeaders headers = new HttpHeaders();
// 响应解析的默认字符集
private Charset charset = Charset.forName("UTF-8");
// 是否检查证书
private Boolean verifySslCert = true;
public void setVerifySslCert(Boolean verifySslCert) {
this.verifySslCert = verifySslCert;
}
public void setCharset(String name) {
this.charset = Charset.forName(name);
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public void setHeaders(HttpHeaders headers) {
this.headers = headers;
}
public String get(String url) throws Exception {
return this.get(url, null);
}
public String get(String url, Object params) throws Exception {
// 参数拼接
List<String> query = new ArrayList<>();
if (params != null) {
JSONObject json = JSON.parseObject(JSON.toJSONString(params));
Iterator iter = json.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object val = entry.getValue();
String str = "";
if (val != null) {
str = val.toString();
}
query.add(key + "=" + URLEncoder.encode(str, "UTF-8"));
}
}
// 查询拼接到URL
String queryString = "";
if (query.size() > 0) {
queryString = String.join("&", query);
if (url.indexOf("?") > 0) {
url += "&" + queryString;
} else {
url += "?" + queryString;
}
}
// 获取请求数据
return request(url, HttpMethod.GET, null);
}
public String post(String url) throws Exception {
return this.post(url, null);
}
public String post(String url, Object params) throws Exception {
return request(url, HttpMethod.POST, params);
}
public String postUrl(String url, Object params) throws Exception {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
LinkedMultiValueMap<String, Object> postParams = new LinkedMultiValueMap<>();
if (params != null) {
JSONObject json = JSON.parseObject(JSON.toJSONString(params));
Iterator iter = json.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object val = entry.getValue();
postParams.add(key,val);
}
}
return request(url, HttpMethod.POST, postParams);
}
public String postjson(String url, Object params) throws Exception {
headers.setContentType(MediaType.APPLICATION_JSON);
return this.post(url, params);
}
public String postxml(String url, Object params) throws Exception {
headers.setContentType(MediaType.APPLICATION_XML);
return this.post(url, params);
}
public String delete(String url, Object params) throws Exception {
return request(url, HttpMethod.DELETE, params);
}
public String deletejson(String url, Object params) throws Exception {
headers.setContentType(MediaType.APPLICATION_JSON);
return this.delete(url, params);
}
public String request(String url, HttpMethod method, Object params) throws Exception {
byte[] data = this.requestByteArray(url, method, params);
if (data == null || data.length == 0) {
return "";
}
return new String(data, this.charset);
}
public byte[] requestByteArray(String url, HttpMethod method, Object params) throws Exception {
log.info("url=======>"+url);
log.info("params=======>"+ JsonUtil.getJsonString(params));
RestTemplate rest;
if (this.verifySslCert) {
rest = new RestTemplate();
} else {
rest = new RestTemplate(RestTemplateConfig.createHttpRequestFactory());
}
rest.getMessageConverters().set(1, new StringHttpMessageConverter(charset));
ResponseEntity<byte[]> res = null;
HttpEntity entity = new HttpEntity(params, this.headers);
if (method == HttpMethod.GET || method == HttpMethod.POST || method == HttpMethod.DELETE) {
res = rest.exchange(url, method, entity, byte[].class);
} else {
throw new JlException("不支持的调用方式");
}
// 返回数据处理
String resEncoding = res.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
Charset resCharset = null;
HttpHeaders resHeaders = res.getHeaders();
if (resHeaders != null) {
MediaType resContentType = resHeaders.getContentType();
if (resContentType != null) {
resCharset = resContentType.getCharset();
}
}
if (resCharset != null) {
this.charset = resCharset;
}
if ("gzip".equalsIgnoreCase(resEncoding)) {
return gunzip(res.getBody(), charset);
}
if (res.getStatusCode().value() == 204) {
return "".getBytes();
}
return res.getBody();
}
public byte[] gunzip(byte[] data, Charset charset) throws Exception {
if (data == null || data.length == 0) {
return null;
}
if (charset == null) {
charset = StandardCharsets.UTF_8;
}
ByteArrayInputStream bais = new ByteArrayInputStream(data);
GZIPInputStream gis = new GZIPInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buf = new byte[4096];
while ((len = gis.read(buf)) >= 0) {
baos.write(buf, 0, len);
}
buf = baos.toByteArray();
String str = new String(buf, charset);
bais.close();
baos.close();
gis.close();
return buf;
}
/**
* 文件下载
*
* @param url
* @param path
*/
public static void downloadFile(String url, String path) throws Exception {
// 文件下载
JlHttp http = new JlHttp();
byte[] data = http.requestByteArray(url, HttpMethod.GET, null);
if (data == null || data.length == 0) {
throw new JlException("文件内容是空的");
}
Jlutil.filePutContents(path, data, false);
}
}