zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
commit | author | age
a18bfa 1 package com.changhong.epc.zuul.util;
Z 2
3 import com.alibaba.fastjson.TypeReference;
4 import com.iemsoft.framework.cloud.core.constant.BaseConst;
5 import com.iemsoft.framework.cloud.core.tools.JSONTool;
6 import com.iemsoft.framework.cloud.core.tools.ObjectUtil;
7 import lombok.extern.slf4j.Slf4j;
8 import org.apache.http.*;
9 import org.apache.http.client.entity.UrlEncodedFormEntity;
10 import org.apache.http.client.methods.HttpGet;
11 import org.apache.http.client.methods.HttpPost;
12 import org.apache.http.config.Registry;
13 import org.apache.http.config.RegistryBuilder;
14 import org.apache.http.conn.socket.ConnectionSocketFactory;
15 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
16 import org.apache.http.conn.ssl.NoopHostnameVerifier;
17 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
18 import org.apache.http.conn.ssl.TrustStrategy;
19 import org.apache.http.entity.StringEntity;
20 import org.apache.http.impl.client.CloseableHttpClient;
21 import org.apache.http.impl.client.HttpClients;
22 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
23 import org.apache.http.message.BasicNameValuePair;
24 import org.apache.http.ssl.SSLContextBuilder;
25 import org.apache.http.util.EntityUtils;
26
27 import java.io.IOException;
28 import java.security.cert.CertificateException;
29 import java.security.cert.X509Certificate;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.concurrent.TimeoutException;
34
35 @Slf4j
36 public class HttpUtil {
37     private static final String HTTP = "http";
38     private static final String HTTPS = "https";
39     private static SSLConnectionSocketFactory sslsf = null;
40     private static PoolingHttpClientConnectionManager cm = null;
41     private static SSLContextBuilder builder = null;
42     public static final String APPLICATION_JSON = "application/json;charset=utf-8";
43     static {
44         try {
45             builder = new SSLContextBuilder();
46             // 全部信任 不做身份鉴定
47             builder.loadTrustMaterial(null, new TrustStrategy() {
48                 @Override
49                 public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
50                     return true;
51                 }
52             });
53             sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
54             Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
55                     .register(HTTP, new PlainConnectionSocketFactory())
56                     .register(HTTPS, sslsf)
57                     .build();
58             cm = new PoolingHttpClientConnectionManager(registry);
59             cm.setMaxTotal(200);//max connection
60         } catch (Exception e) {
61             // System.err.println(e.getMessage());
62         }
63     }
64     
65     public static <T> T get(String url, Map<String, String> header, Class<T> result) throws TimeoutException {
66         try (CloseableHttpClient httpClient = url.startsWith("https") ? getHttpClient() : HttpClients.createDefault()){
67
68             HttpGet httpGet = new HttpGet(url);
69             // 设置头信息
70             if (ObjectUtil.notEmpty(header)) {
71                 for (Map.Entry<String, String> entry : header.entrySet()) {
72                     httpGet.addHeader(entry.getKey(), entry.getValue());
73                 }
74             }
75             HttpResponse httpResponse = httpClient.execute(httpGet);
76             int statusCode = httpResponse.getStatusLine().getStatusCode();
77             if (statusCode == HttpStatus.SC_OK) {
78                 HttpEntity resEntity = httpResponse.getEntity();
79                 String str = EntityUtils.toString(resEntity, BaseConst.PROJECT_CHARSET);
80                 if(ObjectUtil.notEmpty(str)){
81                     return JSONTool.toObj(str, result);
82                 }
83                 return null;
84             } else {
85                 readHttpResponse(httpResponse);
86                 return null;
87             }
88         } catch (Exception e) {
89             throw new TimeoutException();
90         }
91     }
92     
93     /**
94      * httpClient post请求
95      * @param url 请求url
96      * @param header 头部信息
97      * @param param 请求参数 form提交适用
98      * @return 可能为空 需要处理
99      * @throws Exception
100      *
101      */
102     public static <T> T post(String  url, Map<String, String> header, Map<String, ? extends Object> param, Object body, TypeReference<T> type) throws Exception {
103         String result = "";
104         try (CloseableHttpClient httpClient = url.startsWith("https") ? getHttpClient() : HttpClients.createDefault()){
105             log.debug("开始发送请求:{}", url);
106             log.debug("header:{}", JSONTool.toJson(header));
107             log.debug("body  :{}", JSONTool.toJson(body));
108             HttpPost httpPost = new HttpPost(url);
109             // 设置头信息
110             if (ObjectUtil.notEmpty(header)) {
111                 for (Map.Entry<String, String> entry : header.entrySet()) {
112                     httpPost.addHeader(entry.getKey(), entry.getValue());
113                 }
114             }
115             // 设置请求参数
116             if (ObjectUtil.notEmpty(param)) {
117                 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
118                 for (Map.Entry<String, ? extends Object> entry : param.entrySet()) {
119                     //给参数赋值
120                     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
121                 }
122                 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
123                 httpPost.setEntity(urlEncodedFormEntity);
124             }
125             // 设置实体 优先级高
126             if (body != null) {
127                 StringEntity stringEntity = new StringEntity(JSONTool.toJson(body), BaseConst.PROJECT_CHARSET);
128                 stringEntity.setContentType(APPLICATION_JSON);
129                 httpPost.setEntity(stringEntity);
130             }
131             HttpResponse httpResponse = httpClient.execute(httpPost);
132             int statusCode = httpResponse.getStatusLine().getStatusCode();
133             if (statusCode == HttpStatus.SC_OK) {
134                 HttpEntity resEntity = httpResponse.getEntity();
135                 result = EntityUtils.toString(resEntity);
136                 log.debug("response:{}", result);
137             } else {
138                 log.error("请求url:{}", url);
139                 log.error("response:{}", readHttpResponse(httpResponse));
140             }
141         } catch (Exception e) {throw e;
142         }
143         return JSONTool.toObj(result, type);
144     }
145     
146
147     public static String getParam(Map<String, Object> param){
148         if(ObjectUtil.empty(param)){
149             return "";
150         }
151         StringBuilder query = new StringBuilder();
152         for (Map.Entry<String, Object> entry : param.entrySet()) {
153             query.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
154         }
155         query.deleteCharAt(query.length()-1);
156         return query.toString();
157     }
158     
159     public static CloseableHttpClient getHttpClient() {
160         CloseableHttpClient httpClient = HttpClients.custom()
161                 .setSSLSocketFactory(sslsf)
162                 .setConnectionManager(cm)
163                 .setConnectionManagerShared(true)
164                 .build();
165         return httpClient;
166     }
167     public static String readHttpResponse(HttpResponse httpResponse)
168             throws ParseException, IOException {
169         StringBuilder builder = new StringBuilder();
170         // 获取响应消息实体
171         HttpEntity entity = httpResponse.getEntity();
172         // 响应状态
173         builder.append("status:" + httpResponse.getStatusLine());
174         builder.append("headers:");
175         HeaderIterator iterator = httpResponse.headerIterator();
176         while (iterator.hasNext()) {
177             builder.append("\t" + iterator.next());
178         }
179         // 判断响应实体是否为空
180         if (entity != null) {
181             String responseString = EntityUtils.toString(entity);
182             builder.append("response length:" + responseString.length());
183             builder.append("response content:" + responseString.replace("\r\n", ""));
184         }
185         return builder.toString();
186     }
187     
188    
189 }