package com.nova.sankuai.security; import cn.hutool.http.HttpUtil; import com.nova.sankuai.infra.constants.Constants; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName: HttpClientUtil * @Description: */ public class HttpClientUtil { private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); private final static String DEFAULT_CHARSET = "UTF-8"; public static int defaultReTryTimes = 3; private static String tokenString = ""; private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED"; private static CloseableHttpClient httpClient = null; private HttpClient getHttpClient(int maxRetryTimes) { HttpClient httpClient = null; try { httpClient = createSSLClientDefault(); } catch (Exception e) { e.printStackTrace(); } // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000); // httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000); return httpClient; } public static CloseableHttpClient createSSLClientDefault() throws Exception { try { //使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书 // 信任所有 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build(); //NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何 //有效的SSL会话并匹配到目标主机。 HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { e.printStackTrace(); } return HttpClients.createDefault(); } private static HttpClientUtil clientUtils = null; /** * 单例 * * @return HttpClientUtil */ public static HttpClientUtil getInstance() { if (clientUtils == null) { clientUtils = new HttpClientUtil(); } return clientUtils; } private String charSet = DEFAULT_CHARSET; public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } /** * get请求 * * @param url * @return * @throws IOException * @throws ClientProtocolException * @throws Exception */ public String get(String url) throws IOException { return this.get(url, 0); } public String get(String url, int maxRetryTimes) throws IOException { return this.get(url, null, maxRetryTimes); } public String get(String url, Map headers) throws IOException { return this.get(url, headers, 0); } public String get(String url, Map headers, int maxRetryTimes) throws IOException { String result = ""; HttpClient httpClient = this.getHttpClient(maxRetryTimes); HttpGet request = new HttpGet(url); if (headers != null && headers.size() > 0) { for (Map.Entry entry : headers.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } } HttpResponse httpResponse = httpClient.execute(request); // 得到httpResponse的状态响应码 int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { // 得到httpResponse的实体数据 HttpEntity httpEntity = httpResponse.getEntity(); if (httpResponse.getFirstHeader("Content-Encoding") != null && httpResponse.getFirstHeader("Content-Encoding").getValue().equals("gzip")) { result = EntityUtils.toString(new GzipDecompressingEntity(httpEntity), charSet); } else { result = EntityUtils.toString(httpEntity, charSet); } } else { result = "fail"; } logger.info("发起GET请求->url:{},result:{}", url, result); return result; } /** * post请求 * * @param url * @param args * @return * @throws IOException * @throws ClientProtocolException */ public String post(String url, Map args) throws IOException { return this.post(url, args, 0); } public String post(String url, Map args, int maxRetryTimes) throws IOException { return this.post(this.getHttpClient(maxRetryTimes), url, args); } public String post(String url, Map headers, Map args) throws IOException { return this.post(url, headers, args, 0); } public String post(String url, Map headers, Map args, int maxRetryTimes) throws IOException { return this.post(this.getHttpClient(maxRetryTimes), url, headers, args); } public String post(HttpClient httpClient, String url, Map headers, Map args) throws ClientProtocolException, IOException { String result = ""; HttpPost request = new HttpPost(url); List postData = new ArrayList<>(); if (headers != null && headers.size() > 0) { for (Map.Entry entry : headers.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } } if (args != null) { for (Map.Entry entry : args.entrySet()) { postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); // System.out.print(entry.getValue()); } } request.setEntity(new UrlEncodedFormEntity(postData, charSet)); HttpResponse httpResponse = httpClient.execute(request); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { // 得到httpResponse的实体数据 HttpEntity httpEntity = httpResponse.getEntity(); if (httpResponse.getFirstHeader("Content-Encoding") != null && httpResponse.getFirstHeader("Content-Encoding").getValue().equals("gzip")) { result = EntityUtils.toString(new GzipDecompressingEntity(httpEntity), charSet); } else { result = EntityUtils.toString(httpEntity, charSet); } } else { result = "fail"; } logger.info("发起POST请求->url:{},result:{}", url, result); return result; } public String post(HttpClient httpClient, String url, Map args) throws IOException { return this.post(httpClient, url, null, args); /* * String result = ""; HttpPost request = new HttpPost(url); List * postData = new ArrayList(); for (Map.Entry entry : * args.entrySet()) { postData.add(new BasicNameValuePair(entry.getKey(), * entry.getValue())); // System.out.print(entry.getValue()); } request.setEntity(new * UrlEncodedFormEntity(postData, charSet)); HttpResponse httpResponse = * httpClient.execute(request); * * int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == * HttpStatus.SC_OK) { // 得到httpResponse的实体数据 HttpEntity httpEntity = * httpResponse.getEntity(); if (httpResponse.getFirstHeader("Content-Encoding") != null && * httpResponse.getFirstHeader("Content-Encoding").getValue().equals("gzip")) { result = * EntityUtils.toString(new GzipDecompressingEntity(httpEntity), charSet); } else { result = * EntityUtils.toString(httpEntity, charSet); } } return result; */ } /** * post json数据 * * @param url * @param jsonData * @return * @throws ClientProtocolException * @throws IOException */ public String postJsonData(String url, String jsonData) throws IOException { return this.postJsonData(url, jsonData, 0); } /** * 随易花post json数据 * * @param url * @param jsonData * @return * @throws ClientProtocolException * @throws IOException */ public String syhPostJsonData(String url, String jsonData) throws IOException { Map headers = new HashMap<>(); headers.put("User-Agent", "Apifox/1.0.0 (https://apifox.com"); return this.postJsonData(url, jsonData, 0, headers); } /** * post json数据 * * @param url * @param jsonData * @return * @throws ClientProtocolException * @throws IOException */ public String postJsonData(String url, String jsonData, Map headers) throws IOException { return this.postJsonData(url, jsonData, 0, headers); } public String postJsonData(String url, String jsonData, int maxRetryTimes) throws IOException { // logger.info("result->jsonData:{}", jsonData); String result = ""; HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonData, "UTF-8"); entity.setContentType("application/json;charset=UTF-8"); httpPost.setEntity(entity); httpPost.setHeader("accept", "application/json"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.TIME_OUT) .setConnectTimeout(Constants.TIME_OUT).build(); httpPost.setConfig(requestConfig); HttpResponse httpResponse = this.getHttpClient(maxRetryTimes).execute(httpPost); // logger.info("httpResponse->url:{}", httpResponse); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity, charSet); // logger.info("result->url:{}", result); } return result; } public String postJsonData(String url, String jsonData, int maxRetryTimes, Map headers) throws IOException { // logger.info("result->jsonData:{}", jsonData); String result = ""; HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonData, "UTF-8"); entity.setContentType("application/json;charset=UTF-8"); httpPost.setEntity(entity); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.TIME_OUT) .setConnectTimeout(Constants.TIME_OUT).build(); httpPost.setConfig(requestConfig); httpPost.setHeader("accept", "application/json"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); headers.forEach((k, v) -> httpPost.setHeader(k, String.valueOf(v))); HttpResponse httpResponse = this.getHttpClient(maxRetryTimes).execute(httpPost); // logger.info("httpResponse->url:{}", httpResponse); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity, charSet); // logger.info("result->url:{}", result); } return result; } public InputStream filePostData(String url, String jsonData) throws IOException { String result = ""; HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonData, "UTF-8"); entity.setContentType("application/json;charset=UTF-8"); httpPost.setEntity(entity); httpPost.setHeader("accept", "application/json"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); HttpResponse httpResponse = this.getHttpClient(0).execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); return httpEntity.getContent(); } return null; } public InputStream filePostData(String url, String jsonData, Map headers) throws IOException { String result = ""; HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonData, "UTF-8"); entity.setContentType("application/json;charset=UTF-8"); httpPost.setEntity(entity); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(Constants.TIME_OUT) .setConnectTimeout(Constants.TIME_OUT).build(); httpPost.setConfig(requestConfig); httpPost.setHeader("accept", "application/json"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); headers.forEach((k, v) -> httpPost.setHeader(k, String.valueOf(v))); HttpResponse httpResponse = this.getHttpClient(0).execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); return httpEntity.getContent(); } return null; } public static String doPost(String url, String data) { cn.hutool.http.HttpResponse httpResponse = HttpUtil.createPost(url) .header("accept", "application/json") .header("Content-Type", MediaType.APPLICATION_JSON_VALUE) .body(data).execute(); return httpResponse.body(); } /** * POST请求,专门用于储信数据·身份认证 */ public static String doPostChuxin(String url, Map param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (null != param) { List paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8"); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != response) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } }