mitao
2025-02-21 31573d6180d15ef65ed0df9c2732495f40b12663
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
package com.panzhihua.common.utlis;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.client.methods.HttpUriRequest;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ObjectUtils;
 
import com.panzhihua.common.constants.HttpConstant;
 
import lombok.extern.slf4j.Slf4j;
 
import javax.net.ssl.SSLContext;
 
import static com.panzhihua.common.utlis.wx.WXPayConstants.USER_AGENT;
 
/**
 * @program: springcloud_k8s_panzhihuazhihuishequ
 * @description:
 * @author: huang.hongfa weixin hhf9596 qq 959656820
 * @create: 2021-01-08 10:23
 **/
@Slf4j
public class HttpClientUtil {
    /**
     * 通过post方式调用http接口
     * 
     * @param url
     *            url路径
     * @param jsonParam
     *            json格式的参数
     * @param reSend
     *            重发次数
     * @param headerKey
     *            header键值
     * @param headerValue
     *            headervalue
     * @return
     * @throws Exception
     */
    public static String sendPostByJson(String url, String jsonParam, int reSend, String headerKey,
        String headerValue) {
        // 声明返回结果
        String result = "";
        // 开始请求API接口时间
        long startTime = System.currentTimeMillis();
        // 请求API接口的响应时间
        long endTime = 0L;
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        HttpClient httpClient = null;
        try {
            // 创建连接
            httpClient = HttpClientFactory.getInstance().getHttpClient();
            // 设置请求头和报文
            HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
            Header header = new BasicHeader("Accept-Encoding", null);
            httpPost.setHeader(header);
            if (!ObjectUtils.isEmpty(headerKey)) {
                httpPost.setHeader(headerKey, headerValue);
            }
            // 设置报文和通讯格式
            StringEntity stringEntity = new StringEntity(jsonParam, HttpConstant.UTF8_ENCODE);
            stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
            stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
//            log.info("请求{}接口的参数为{}", url, jsonParam);
            // 执行发送,获取相应结果
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            log.error("请求{}接口出现异常", url, e);
            if (reSend > 0) {
                log.info("请求{}出现异常:{},进行重发。进行第{}次重发", url, e.getMessage(), (HttpConstant.REQ_TIMES - reSend + 1));
                result = sendPostByJson(url, jsonParam, reSend - 1, headerKey, headerValue);
                if (result != null && !"".equals(result)) {
                    return result;
                }
            }
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                log.error("http请求释放资源异常", e);
            }
        }
        // 请求接口的响应时间
        endTime = System.currentTimeMillis();
//        log.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));
        return result;
 
    }
 
    /**
     * 使用http请求调用接口,参数类型为xml
     * 
     * @param urlStr
     *            请求地址
     * @param data
     *            请求参数
     * @return 调用结果
     */
    public static String httpsRequest(String urlStr, String data) {
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            // con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
 
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            log.info("urlStr=" + urlStr);
            log.info("xmlInfo=" + data);
            out.write(new String(data.getBytes("UTF-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = "";
            StringBuffer sb = new StringBuffer();
            for (line = br.readLine(); line != null; line = br.readLine()) {
                sb.append(line);
            }
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     * http请求工具类,get请求
     *
     * @param url
     * @param params
     * @param resonseCharSet
     * @return
     * @throws Exception
     */
    public static String httpGet(String url, Map<String, Object> params, String... resonseCharSet) throws Exception {
        DefaultHttpClient defaultHttpClient = null;
        BufferedReader bufferedReader = null;
        try {
            defaultHttpClient = new DefaultHttpClient();
            if (params != null) {
                StringBuilder stringBuilder = new StringBuilder();
                Iterator<String> iterator = params.keySet().iterator();
                String key;
                while (iterator.hasNext()) {
                    key = iterator.next();
                    Object val = params.get(key);
                    if (val instanceof List) {
                        List v = (List)val;
                        for (Object o : v) {
                            stringBuilder.append(key).append("=").append(o.toString()).append("&");
                        }
                    } else {
                        stringBuilder.append(key).append("=").append(val.toString()).append("&");
                    }
                }
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                url = url + "?" + stringBuilder.toString();
                log.info("url:{}", url);
            }
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json;charset=ut-8");
            HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() != 200) {
                String errorLog = "请求失败,errorCode:" + httpResponse.getStatusLine().getStatusCode();
                log.info("errorLog:{}"+errorLog);
                throw new Exception(url + errorLog);
            }
            // 读取返回信息
            String charSet = "utf-8";
            if (resonseCharSet != null && resonseCharSet.length > 0)
                charSet = resonseCharSet[0];
            String output;
            bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), charSet));
 
            StringBuilder dataBuilder = new StringBuilder();
            while ((output = bufferedReader.readLine()) != null) {
                dataBuilder.append(output);
            }
            return dataBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (defaultHttpClient != null)
                defaultHttpClient.getConnectionManager().shutdown();
            if (bufferedReader != null)
                bufferedReader.close();
        }
    }
 
 
 
    /**
     * http请求工具类,post请求
     *
     * @param url
     *            url
     * @param param
     *            参数值 仅支持String
     * @return
     * @throws Exception
     */
    public static String httpPost(String url, String param) throws Exception {
        DefaultHttpClient defaultHttpClient = null;
        BufferedReader bufferedReader = null;
        try {
            defaultHttpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            if (StringUtils.isNotBlank(param)) {
                log.info("参数值:{}", param);
                HttpEntity httpEntity = new StringEntity(param, "utf-8");
                httpPost.setEntity(httpEntity);
            }
            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() != 200) {
                String errorLog = "请求失败,errorCode:" + httpResponse.getStatusLine().getStatusCode();
                log.info(errorLog);
                throw new Exception(url + errorLog);
            }
            // 读取返回信息
            String output;
            bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8"));
            StringBuilder stringBuilder = new StringBuilder();
            while ((output = bufferedReader.readLine()) != null) {
                stringBuilder.append(output);
            }
            log.info("调用微信接口返回的参数:" + stringBuilder.toString());
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (defaultHttpClient != null)
                defaultHttpClient.getConnectionManager().shutdown();
            if (bufferedReader != null)
                bufferedReader.close();
        }
    }
 
 
 
    // HTTP GET请求
    public static String sendGet(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //默认值GET
        con.setRequestMethod("GET");
        //添加请求头
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        log.info("发送 'GET' 请求到 URL:{}" + url);
        log.info("Response Code:{}" + responseCode);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        //打印结果
        log.info("uu洗车返回:{}"+response.toString());
        return response.toString();
    }
 
    /**
     * http请求工具类,post请求
     *
     * @param url
     *            url
     * @param param
     *            参数值 仅支持String
     * @return
     * @throws Exception
     */
    public static String httpPostAndToken(String url, String param,Map headerMap) throws Exception {
        DefaultHttpClient defaultHttpClient = null;
        BufferedReader bufferedReader = null;
        try {
            defaultHttpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
//            httpPost.setHeader("Authorization", headerMap.get("Authorization").toString());
//            httpPost.setHeader("Host", headerMap.get("Host").toString());
 
            for (Object key : headerMap.keySet()) {
                httpPost.setHeader(key.toString(), headerMap.get(key).toString());
            }
            if (StringUtils.isNotBlank(param)) {
                log.info("参数值:{}", param);
                HttpEntity httpEntity = new StringEntity(param, "utf-8");
                httpPost.setEntity(httpEntity);
//                httpPost.setHeader("Content-Length", String.valueOf(httpEntity.getContentLength()));
            }
            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() != 200) {
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                String errorLog = "请求失败,errorCode:" + httpResponse.getStatusLine().getStatusCode();
                log.info(errorLog);
                throw new Exception(url + errorLog);
            }
            // 读取返回信息
            String output;
            bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8"));
            StringBuilder stringBuilder = new StringBuilder();
            while ((output = bufferedReader.readLine()) != null) {
                stringBuilder.append(output);
            }
            log.info("调用接口返回的参数:" + stringBuilder.toString());
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (defaultHttpClient != null)
                defaultHttpClient.getConnectionManager().shutdown();
            if (bufferedReader != null)
                bufferedReader.close();
        }
    }
 
    public static void main(String[] args) throws IOException {
        DefaultHttpClient  defaultHttpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("https://dptest.d-power.com.cn:14404/v1/face");
//        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Authorization", "DpToken P3JHgjLbyljfLrFnS9OZbATRJmacdt4b");
        httpPost.setHeader("Host", "123.60.2.66");
//        httpPost.setHeader("Content-Length", String.valueOf(entity.getContentLength()));
 
//        httpPost.setHeader("User-Agent", "Apache-HttpClient/4.5.12 (Java/1.8.0_162)[\\r][\\n]");
        httpPost.setEntity(new StringEntity("{\"positions\":[{\"role\":\"occupant\",\"communityId\":\"64f99b2ed26106d4f0fe93f4\",\"unitId\":\"64f99b2ed26106d4f0fe93f7\"}],\"tel\":\"15696695118\",\"name\":\"四月里3\",\"timeout\":10,\"image\":\"fsdfsdfsdf\"}", "utf-8"));
//        httpPost.setHeader("Content-Length", String.valueOf(entity.getContentLength()));
        HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
        System.out.println(httpResponse.getEntity());
    }
 
    /**
     * get请求
     * 
     * @param url
     *            请求地址(get请求时参数自己组装到url上)
     * @param headerMap
     *            请求头
     * @return 响应文本
     */
    public static String get(String url, Map<String, String> headerMap, String param) {
        // 请求地址,以及参数设置
        HttpPost post = new HttpPost(url);
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        if (StringUtils.isNotBlank(param)) {
            log.info("参数值:{}", param);
            HttpEntity httpEntity = new StringEntity(param, "utf-8");
            post.setEntity(httpEntity);
        }
        // 执行请求,获取相应
        return getRespString(post);
    }
 
    /**
     * get请求
     *
     * @param url
     *            请求地址(get请求时参数自己组装到url上)
     * @param headerMap
     *            请求头
     * @return 响应文本
     */
    public static String getUU(String url, Map<String, String> headerMap, String param) {
        // 请求地址,以及参数设置
        HttpPost post = new HttpPost(url);
 
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
 
        CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
 
 
        //请求超时时间设置
        post.setConfig(RequestConfig.custom()// 连接超时时间
                .setConnectTimeout(5000)
        // 请求超时时间
                .setConnectionRequestTimeout(5000)
        // Socket读取超时时间
                .setSocketTimeout(5000)
        // 是否允许重定向
                .setRedirectsEnabled(false)
                .build());
 
         //发送请求
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("request error. ");
 
        }
        HttpEntity entity = response.getEntity();
        try {
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                return EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return null;
    }
 
 
 
    /**
     * 获取响应信息(String)
     */
    public static String getRespString(HttpUriRequest request) {
        // 获取响应流
        InputStream in = getRespInputStream(request);
 
        StringBuilder sb = new StringBuilder();
        String line;
 
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str = sb.toString();
        return str;
    }
 
    /**
     * 获取响应信息(InputStream)
     */
    public static InputStream getRespInputStream(HttpUriRequest request) {
        // 获取响应对象
        HttpResponse response = null;
        try {
            response = HttpClients.createDefault().execute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response == null) {
            return null;
        }
        // 获取Entity对象
        HttpEntity entity = response.getEntity();
        // 获取响应信息流
        InputStream in = null;
        if (entity != null) {
            try {
                in = entity.getContent();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return in;
    }
 
    /**
     * 退款请求微信
     * @param url   请求地址
     * @param data  请求数据
     * @param mchId 商户id
     * @param isTest    是否是测试
     * @return  退款结果
     * @throws Exception    抛出异常
     */
    public static String doRefund(String url, String data,String mchId,Boolean isTest) throws Exception{
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        //P12文件目录 证书路径,这里需要你自己修改,linux下还是windows下的根路径
        String filepath = "/mnt/data/refund/huacheng/";
 
        System.out.println("filepath->"+filepath);
        FileInputStream instream = new FileInputStream(filepath+"apiclient_cert.p12");
        try {
            keyStore.load(instream, mchId.toCharArray());//这里写密码..默认是你的MCHID
        } finally {
            instream.close();
        }
 
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mchId.toCharArray())//这里也是写密码的
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httpost = new HttpPost(url); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
 
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info("请求微信退款接口返回结果:" + JSONObject.toJSONString(jsonStr));
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
 
    }
}