ab
2024-11-05 bead00668eebce8d39d027515d564376de2f5978
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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<String, String> headers) throws IOException {
        return this.get(url, headers, 0);
    }
 
    public String get(String url, Map<String, String> 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<String, String> 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<String, String> args) throws IOException {
        return this.post(url, args, 0);
    }
 
    public String post(String url, Map<String, String> args, int maxRetryTimes) throws IOException {
        return this.post(this.getHttpClient(maxRetryTimes), url, args);
    }
 
    public String post(String url, Map<String, String> headers, Map<String, String> args) throws IOException {
        return this.post(url, headers, args, 0);
    }
 
    public String post(String url, Map<String, String> headers, Map<String, String> args, int maxRetryTimes) throws IOException {
        return this.post(this.getHttpClient(maxRetryTimes), url, headers, args);
    }
 
    public String post(HttpClient httpClient, String url, Map<String, String> headers, Map<String, String> args)
            throws ClientProtocolException, IOException {
        String result = "";
        HttpPost request = new HttpPost(url);
        List<BasicNameValuePair> postData = new ArrayList<>();
 
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }
        }
        if (args != null) {
            for (Map.Entry<String, String> 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<String, String> args) throws IOException {
        return this.post(httpClient, url, null, args);
        /*
         * String result = ""; HttpPost request = new HttpPost(url); List<BasicNameValuePair>
         * postData = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, String> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (null != param) {
                List<NameValuePair> 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;
    }
 
}