111
童刚
2022-08-03 72e72b8733cd2fd063f251bc7450c9e36b01f352
提交 | 用户 | age
72e72b 1 package com.hz.util.http.dto;
2
3 import org.apache.commons.lang.StringUtils;
4 import org.apache.http.HttpEntity;
5 import org.apache.http.NameValuePair;
6 import org.apache.http.client.config.RequestConfig;
7 import org.apache.http.client.entity.UrlEncodedFormEntity;
8 import org.apache.http.client.methods.CloseableHttpResponse;
9 import org.apache.http.client.methods.HttpGet;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
12 import org.apache.http.entity.StringEntity;
13 import org.apache.http.impl.client.CloseableHttpClient;
14 import org.apache.http.impl.client.HttpClientBuilder;
15 import org.apache.http.impl.client.HttpClients;
16 import org.apache.http.message.BasicNameValuePair;
17 import org.apache.http.ssl.SSLContextBuilder;
18 import org.apache.http.ssl.TrustStrategy;
19 import org.apache.http.util.EntityUtils;
20
21 import javax.net.ssl.SSLContext;
22 import javax.servlet.http.HttpServletRequest;
23 import java.io.IOException;
24 import java.security.KeyManagementException;
25 import java.security.KeyStoreException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.cert.CertificateException;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Map;
32
33 public class HttpClientUtils {
34
35     /** 获取Http客户端 */
36     private static final CloseableHttpClient httpClient;
37     /** 设置默认编码 */
38     public static final String CHARSET = "UTF-8";
39
40     /** 初始化超时时间配置,并配置生成默认httpClient对象 */
41     static {
42         RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
43         httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
44     }
45
46     public static String doGet(String url, Map<String, String> params) {
47         return doGet(url, params, CHARSET);
48     }
49
50     public static String doPost(String url, Map<String, String> params) {
51         return doPost(url, params, CHARSET);
52     }
53
54     public static String doGetSSL(String url, Map<String, String> params) {
55         return doGetSSL(url, params, CHARSET);
56     }
57
58     /**
59      * 获取ip地址
60      */
61     public static String getIp(HttpServletRequest request) {
62         String ip = request.getHeader("x-forwarded-for");
63         System.out.println("x-forwarded-for ip: " + ip);
64         if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
65             // 多次反向代理后会有多个ip值,第一个ip才是真实ip
66             if (ip.contains(",")) {
67                 ip = ip.split(",")[0];
68             }
69         }
70         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
71             ip = request.getHeader("Proxy-Client-IP");
72         }
73         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
74             ip = request.getHeader("WL-Proxy-Client-IP");
75         }
76         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
77             ip = request.getHeader("HTTP_CLIENT_IP");
78         }
79         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
80             ip = request.getHeader("HTTP_X_FORWARDED_FOR");
81         }
82         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
83             ip = request.getHeader("X-Real-IP");
84         }
85         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
86             ip = request.getRemoteAddr();
87         }
88         return ip;
89     }
90
91     /**
92      * HTTP GET获取内容
93      *
94      * @param url     请求地址
95      * @param params  请求参数
96      * @param charset 编码(UTF-8)
97      * @return String
98      */
99     public static String doGet(String url, Map<String, String> params, String charset) {
100         String result = null;
101         if (StringUtils.isBlank(url)) {
102             return null;
103         }
104         //响应模型
105         CloseableHttpResponse response = null;
106         try {
107             //将请求参数拼接url地址后
108             if (params != null && !params.isEmpty()) {
109                 List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
110                 for (Map.Entry<String, String> entry : params.entrySet()) {
111                     String value = entry.getValue();
112                     if (value != null) {
113                         pairs.add(new BasicNameValuePair(entry.getKey(), value));
114                     }
115                 }
116                 url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
117             }
118             //创建http get请求
119             HttpGet httpGet = new HttpGet(url);
120             //由客户端执行get请求
121             response = httpClient.execute(httpGet);
122             //获取响应状态
123             int statusCode = response.getStatusLine().getStatusCode();
124             if (statusCode != 200) {
125                 httpGet.abort();
126                 throw new RuntimeException("HttpClient,error status code :" + statusCode);
127             }
128             //从响应模型中获取响应实体
129             HttpEntity entity = response.getEntity();
130             if (entity != null) {
131                 result = EntityUtils.toString(entity, charset);
132             }
133             //关闭HttpEntity流
134             EntityUtils.consume(entity);
135             return result;
136         } catch (Exception e) {
137             e.printStackTrace();
138         } finally {
139             try {
140                 if (response != null) {
141                     response.close();
142                 }
143             } catch (IOException e) {
144                 e.printStackTrace();
145             }
146         }
147         return result;
148     }
149
150     public static String doPost(String url, String params, String charset) {
151         String result = null;
152         //响应模型
153         CloseableHttpResponse response = null;
154         try {
155             //创建http post请求
156             HttpPost httpPost = new HttpPost(url);
157             if (params != null && !"".equals(params)) {
158                 StringEntity stringEntity = new StringEntity(params);
159                 stringEntity.setContentType("application/json");
160                 stringEntity.setContentEncoding(charset);
161                 httpPost.setEntity(stringEntity);
162                 //由客户端执行post请求
163                 response = httpClient.execute(httpPost);
164                 HttpEntity entity = response.getEntity();
165                 if (entity != null) {
166                     result = EntityUtils.toString(entity, charset);
167                 }
168                 //关闭HttpEntity流
169                 EntityUtils.consume(entity);
170             }
171         } catch (Exception e) {
172             e.printStackTrace();
173         } finally {
174             try {
175                 if (response != null) {
176                     response.close();
177                 }
178             } catch (IOException e) {
179                 e.printStackTrace();
180             }
181         }
182         return result;
183     }
184
185     /**
186      * HTTP POST获取内容
187      *
188      * @param url     请求地址
189      * @param params  请求参数
190      * @param charset 编码(UTF-8)
191      * @return String
192      */
193     public static String doPost(String url, Map<String, String> params, String charset) {
194         String result = null;
195         if (StringUtils.isBlank(url)) {
196             return null;
197         }
198         //请求参数
199         List<NameValuePair> pairs = null;
200         //响应模型
201         CloseableHttpResponse response = null;
202         try {
203             if (params != null && !params.isEmpty()) {
204                 pairs = new ArrayList<NameValuePair>(params.size());
205                 for (Map.Entry<String, String> entry : params.entrySet()) {
206                     String value = entry.getValue();
207                     if (value != null) {
208                         pairs.add(new BasicNameValuePair(entry.getKey(), value));
209                     }
210                 }
211             }
212             //创建http post请求
213             HttpPost httpPost = new HttpPost(url);
214             if (pairs != null && pairs.size() > 0) {
215                 httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
216             }
217             //由客户端执行post请求
218             response = httpClient.execute(httpPost);
219             //获取响应状态
220             int statusCode = response.getStatusLine().getStatusCode();
221             if (statusCode != 200) {
222                 httpPost.abort();
223                 throw new RuntimeException("HttpClient,error status code :" + statusCode);
224             }
225             //从响应模型中获取响应实体
226             HttpEntity entity = response.getEntity();
227             if (entity != null) {
228                 result = EntityUtils.toString(entity, charset);
229             }
230             //关闭HttpEntity流
231             EntityUtils.consume(entity);
232         } catch (Exception e) {
233             e.printStackTrace();
234         } finally {
235             try {
236                 if (response != null) {
237                     response.close();
238                 }
239             } catch (IOException e) {
240                 e.printStackTrace();
241             }
242         }
243         return result;
244     }
245
246     /**
247      * HTTPS GET 获取内容
248      *
249      * @param url     请求的url地址 ?之前的地址
250      * @param params  请求的参数
251      * @param charset 编码格式
252      * @return 页面内容
253      */
254     public static String doGetSSL(String url, Map<String, String> params, String charset) {
255         if (StringUtils.isBlank(url)) {
256             return null;
257         }
258         String result = null;
259         CloseableHttpResponse response = null;
260         try {
261             if (params != null && !params.isEmpty()) {
262                 List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
263                 for (Map.Entry<String, String> entry : params.entrySet()) {
264                     String value = entry.getValue();
265                     if (value != null) {
266                         pairs.add(new BasicNameValuePair(entry.getKey(), value));
267                     }
268                 }
269                 url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
270             }
271             HttpGet httpGet = new HttpGet(url);
272             // https  注意这里获取https内容,使用了忽略证书的方式,当然还有其他的方式来获取https内容
273             CloseableHttpClient httpsClient = HttpClientUtils.createSSLClientDefault();
274             response = httpsClient.execute(httpGet);
275             int statusCode = response.getStatusLine().getStatusCode();
276             if (statusCode != 200) {
277                 httpGet.abort();
278                 throw new RuntimeException("HttpClient,error status code :" + statusCode);
279             }
280             HttpEntity entity = response.getEntity();
281             if (entity != null) {
282                 result = EntityUtils.toString(entity, charset);
283             }
284             EntityUtils.consume(entity);
285             return result;
286         } catch (Exception e) {
287             e.printStackTrace();
288         } finally {
289             try {
290                 if (response != null) {
291                     response.close();
292                 }
293             } catch (IOException e) {
294                 e.printStackTrace();
295             }
296         }
297         return result;
298     }
299
300     /**
301      * 这里创建了忽略整数验证的CloseableHttpClient对象
302      */
303     public static CloseableHttpClient createSSLClientDefault() {
304         try {
305             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
306                 // 信任所有
307                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
308                     return true;
309                 }
310             }).build();
311             SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(sslContext);
312             return HttpClients.custom().setSSLSocketFactory(ssl).build();
313         } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
314             e.printStackTrace();
315         }
316         return HttpClients.createDefault();
317     }
318
319 }