doum
昨天 6c12dd77bc481aeabec568bfed3dd68e81b80f8b
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
package com.doumee.keyCabinet.utils;
 
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
 
 
/**
 * @Description
 * @ClassName   OkHttpClientUtil
 * @Author
 * @Copyright
 */
public class OkHttpClientUtil {
 
    //private static Logger logger = LoggerFactory.getLogger(OkHttpClientUtil.class);
    //private static String JSON = "application/json; charset=utf-8";
    private static String MEDIA_TYPE_JSON= "application/x-www-form-urlencoded; charset=utf-8";
    /**使用volatile双重校验锁**/
    private static volatile Semaphore semaphore = null;
    private static volatile OkHttpClient okHttpClient = null;
 
    /**建立单例模式*/
    public static  Semaphore getSemaphoreInstance(){
        //只能0个线程同时访问
        synchronized (OkHttpClientUtil.class) {
            if (semaphore == null) {
                semaphore = new Semaphore(0);
            }
        }
        return semaphore;
    }
 
 
    /**建立单例模式*/
    public static  OkHttpClient getInstance(){
        synchronized (OkHttpClientUtil.class) {
            if (okHttpClient == null) {
                //这里是以毫秒为单位,1000 毫秒 = 1秒
                okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(5000, TimeUnit.SECONDS)// 设置超时时间
                        .readTimeout(5000, TimeUnit.SECONDS)// 设置读取超时时间
                        .writeTimeout(5000, TimeUnit.SECONDS)// 设置写入超时时间
                        .build();
            }
        }
        return okHttpClient;
    }
 
 
    /**
     * @Description 求在子线程发起网络请求
     * @param url 请求url地址
     * @param params  请求body参数
     * @param okHttpClientCall 回调接口
     * @throws IOException 参数
     * @return void 返回类型
     */
    public  static void createAsycHttpGet(String url,Map<String,Object> params,String contentType,final IOkHttpClientCallBack okHttpClientCall)  {
        // 创建请求对象
        Call call = createCall(url, params);
 
        //发起异步的请求
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response!=null && response.isSuccessful()) {
                    String string = response.body().string();
                    okHttpClientCall.onSuccessful(string);
                }
            }
            @Override
            public void onFailure(Call call, IOException e) {
                String errorLog = getCurrentClassName()+"#createHttpGet,请求异常,异常信息为:"+e.getMessage();
                //logger.error("@see "+errorLog);
            }
        });
    }
 
    /**
     * @Description 求在子线程发起网络请求
     * @param url 请求url地址
     * @param params  请求body参数
     * @throws IOException 参数
     * @return void 返回类型
     */
    public static String createAsycHttpGet(String url,Map<String,Object> params,String contentType)  {
        final StringBuilder buffer = new StringBuilder("");
        try {
            // 创建请求对象
            Call call = createCall(url, params);
 
            //发起异步的请求
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
 
                    if (response!=null && response.isSuccessful()) {
                        String string = response.body().string();
                        buffer.append(string);
                        getSemaphoreInstance().release();
                    }
                }
                @Override
                public void onFailure(Call call, IOException e) {
                    String errorLog = getCurrentClassName()+"#createHttpGet,请求异常,异常信息为:"+e.getMessage();
                    //logger.error("@see "+errorLog);
                }
            });
            getSemaphoreInstance().acquire();//获取许可
            return buffer.toString();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
 
    /**
     * @Description 求在子线程发起网络请求
     * @param url 请求url地址
     * @param params  请求body参数
     * @throws IOException 参数
     * @return void 返回类型
     */
    public static String createHttpGet(String url,Map<String,Object> params,String contentType)  {
        try {
            // 创建请求对象
            Call call = createCall(url, params);
 
            Response response = call.execute();
            if (response!=null && response.isSuccessful() && response.body().string()!=null) {
                //Collection<String> readLines = IOUtil.readLines(byteStream);
                //System.out.println(readLines);
                return convertToString(response.body().byteStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
 
 
    /**
     * @Description convertStreamToString
     * @param is
     * @return 参数
     * @return String 返回类型
     * @throws
     */
    public static String convertToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder buffer = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\r");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }
 
    /**
     * @Description convertStr
     * @param is
     * @return
     * @throws IOException 参数
     * @return String 返回类型
     * @throws
     */
    public static String convertStr(InputStream is) throws IOException {
        OutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }
    /**
     * @Description 创建异步表单Body参数的post请求处理
     * @param url   请求链接
     * @param params 请求表单body参数
     * @param okHttpClientCall 参数  回调接口
     * @return void 返回类型
     */
    public static void createPostByAsynWithForm(String url,Map<String,Object> params,final IOkHttpClientCallBack okHttpClientCall)  {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : params.keySet()) {
            builder.add(key, params.get(key).toString());
        }
        RequestBody formBody = builder.build();
        //logger.info("@see"+getCurrentClassName()+"请求url"+url+",请求参数:"+formBody);
 
        Request request = new Request.Builder().url(url).post(formBody).build();
        // 创建请求对象
        Call call = getInstance().newCall(request);
        //发起异步的请求
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
 
                if (response!=null && response.isSuccessful()) {
                    String string = response.body().string();
                    okHttpClientCall.onSuccessful(string);
                }
            }
 
            @Override
            public void onFailure(Call call, IOException e) {
                String errorLog = getCurrentClassName()+"#createPostByAsynWithForm,请求异常,异常信息为:"+e.getMessage();
                //okHttpClientCall.onFailure(errorLog);
                //logger.error("@see "+errorLog);
            }
        });
    }
 
 
    /**
     * @Description 创建异步表单Body参数的post请求处理
     * @param url   请求链接
     * @param params 请求表单body参数
     * @return
     * @return void 返回类型
     */
    public static String createPostByAsynWithForm(String url,Map<String,Object> params)  {
        final StringBuilder buffer = new StringBuilder("");
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : params.keySet()) {
                builder.add(key, params.get(key).toString());
            }
            RequestBody formBody = builder.build();
            //logger.info("@see"+getCurrentClassName()+"请求url"+url+",请求参数:"+formBody);
 
            Request request = new Request.Builder().url(url).post(formBody).build();
            // 创建请求对象
            Call call = getInstance().newCall(request);
            //发起异步的请求
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
 
                    if (response!=null && response.isSuccessful()) {
                        String string = response.body().string();
                        buffer.append(string);
                        getSemaphoreInstance().release();
                    }
                }
 
                @Override
                public void onFailure(Call call, IOException e) {
                    String errorLog = getCurrentClassName()+"#createPostByAsynWithForm,请求异常,异常信息为:"+e.getMessage();
                    //logger.error("@see "+errorLog);
                }
            });
            getSemaphoreInstance().acquire();
            return buffer.toString();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
 
 
 
    /**
     * okHttp createCall
     * @param url  接口地址
     * @param params   请求参数
     */
    private static Call createCall(String url, Map<String, Object> params) {
        //补全请求地址,【%s?%s或者%s/%s的使用】第一个%s代表第一个参数,第二个?代表是请求地址的?后面%s代表是组装戳参数,如:
        //http://localhost:8080/api/test.do?userId=1212&deviceInfo=PC
        String requestUrl = String.format("%s?%s", url, concatParams(params).toString());
        //创建一个请求
        Request request = new Request.Builder().url(requestUrl).build();
        return  getInstance().newCall(request);
    }
 
 
    /**
     * @param url
     * @param reqMap
     * @param contentType
     * @return 参数
     * @return String 返回类型
     */
    public static String createHttpPost(String url,Map<String,Object> reqMap,String contentType) {
        try {
            RequestBody body = createRequestBody(contentType, reqMap);
            //logger.info("@see"+getCurrentClassName()+"#createHttpPost,请求url"+url+",请求参数:"+body.toString());
            final Request request = new Request.Builder().url(url).post(body).build();
            // 创建请求对象
            final Call call = getInstance().newCall(request);
            Response response = call.execute();
            if (response!=null && response.isSuccessful()) {
                return convertStr(response.body().byteStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
 
    }
 
    /**
     * @param url 参数
     * @return void 返回类型
     */
    public static String createAsycHttpPost(String url,Map<String,Object> reqMap,String contentType) {
        final StringBuilder buffer = new StringBuilder("");
        try {
            final RequestBody body = createRequestBody(contentType, reqMap);
 
            //logger.info("@see"+getCurrentClassName()+"#createHttpPost,请求url"+url+",请求参数:"+body.toString());
            final Request request = new Request.Builder().url(url).post(body).build();
            // 创建请求对象
            final Call call = getInstance().newCall(request);
 
            // 发起请求
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    String errorLog = getCurrentClassName()+"#createHttpPost,请求异常,异常信息为:"+e.getMessage();
                    //logger.error("@see "+errorLog);
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response!=null && response.isSuccessful()) {
                        if(response.body().string()!=null){
                            String string = response.body().string();
                            buffer.append(string);
                            getSemaphoreInstance().release();//释放
                        }
                    }
                }
            });
            getSemaphoreInstance().acquire();//接受
            return  buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
 
    /**
     * @param url 参数
     * @return void 返回类型
     */
    public static void createAsycHttpPost(String url,String postjson,Map<String,String> headMap,final IOkHttpClientCallBack okHttpClientCall) {
        Headers setHeaders = SetHeaders(headMap);
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        final RequestBody requestBody = RequestBody.create(mediaType, postjson);;
        final Request request = new Request.Builder().url(url).headers(setHeaders).post(requestBody).build();
        // 创建请求对象
        final Call call = getInstance().newCall(request);
        // 发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String errorLog = getCurrentClassName()+"#createHttpPost,请求异常,异常信息为:"+e.getMessage();
                //logger.error("@see "+errorLog);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response!=null && response.isSuccessful()) {
                    if(response.body()!=null&&response.body().string()!=null){
                        Object obj = response.body().string();
                        String retBody = response.body().string();
                        okHttpClientCall.onSuccessful(retBody);
                    }
                }
            }
        });
    }
 
    public static void asynPost(String url,String postjson,Map<String,String> headMap,final IOkHttpClientCallBack okHttpClientCall) {
        Headers setHeaders = SetHeaders(headMap);
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        final RequestBody requestBody = RequestBody.create(mediaType, postjson);
        final Request request = new Request.Builder()
                .url(url)
                .headers(setHeaders)
                .post(requestBody)
                .build();
        final Call client = getInstance().newCall(request);
        client.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okHttpClientCall.onError();
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                if (body != null) {
                    //LogUtils.d("asynPost==>", body.string());
                    okHttpClientCall.onSuccessful(body.string());
                }else {
                    okHttpClientCall.onError();
                }
            }
        });
    }
 
    /**
     *
     * @param contentType  请求头header属性
     * @param params       请求参数
     * @return 参数
     * @return RequestBody 返回类型
     */
    private static RequestBody createRequestBody(String contentType,Map<String,Object> params){
        MediaType type = MediaType.parse(contentType);
        String paramStrs = concatParams(params).toString();
        return RequestBody.create(type, paramStrs);
    }
 
 
 
    /**
     * @param params
     * @return 参数
     * @return StringBuilder 返回类型
     */
    private static StringBuilder concatParams(Map<String, Object> params) {
        StringBuilder builder = new StringBuilder("");//请求参数为空给一个默认值空字符串
        //判断是空
        if (params.size()>0) {
            int i = 0;
            for (String key : params.keySet()) {
                Object value = params.get(key);
                builder.append(i != 0 ? "&" : "");
                builder.append(key + "=" + value);
                i++;
            }
        }
        return builder;
    }
 
 
    /**
     * @param url
     * @param reqMap
     * @param contentType 参数
     * @return void 返回类型
     * @throws
     */
    public static String createHttpsPost(String url,Map<String,Object> reqMap,String contentType) {
        final StringBuilder buffer = new StringBuilder("");
        /**忽略SSL协议证书*/
 
        OkHttpClient build = new OkHttpClient.Builder().sslSocketFactory(createSSLSocketFactory()).hostnameVerifier(new TrustAllHostnameVerifier()).build();
 
        final RequestBody body = createRequestBody(contentType, reqMap);
 
        final Request request  = new Request.Builder().url(url).post(body).build();
        final Call    call     = build.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException
            {
                String res = response.body().string();
                buffer.append(res);
                getSemaphoreInstance().release();//释放
            }
        });
 
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        return  buffer.toString();
    }
 
    /**
     * @param url
     * @return void 返回类型
     * @throws
     */
    public static String createHttpsPostByjson(String url,String postjson, Map<String, String> headMap) {
        final StringBuilder buffer = new StringBuilder("");
        /**忽略SSL协议证书*/
        Headers setHeaders = SetHeaders(headMap);
        OkHttpClient build = new OkHttpClient.Builder().sslSocketFactory(createSSLSocketFactory()).hostnameVerifier(new TrustAllHostnameVerifier()).build();
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        final RequestBody requestBody = RequestBody.create(mediaType, postjson);;
 
        final Request request  = new Request.Builder().url(url).headers(setHeaders).post(requestBody).build();
        final Call    call     = build.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException
            {
                String res = response.body().string();
                buffer.append(res);
                getSemaphoreInstance().release();//释放
            }
        });
 
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        return  buffer.toString();
    }
 
    public static Headers SetHeaders(Map<String, String> headersParams) {
        Headers headers = null;
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        if (headersParams.size()>0) {
            Iterator<String> iterator = headersParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                headersbuilder.add(key, headersParams.get(key));
            }
        }
        headers = headersbuilder.build();
        return headers;
    }
 
    /**
     * @Author    liangjl
     * @Copyright (c) All Rights Reserved, 2018.
     */
    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
 
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
 
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
 
    /**
     * @Description    验证所有主机
     * @ClassName  TrustAllHostnameVerifier
     * @Copyright (c) All Rights Reserved, 2018.
     */
    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
 
    /**
     * @Description createSSLSocketFactory
     * @return 参数
     * @return SSLSocketFactory 返回类型
     * @throws
     */
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[] { new TrustAllCerts() }, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }
 
    /**
     *
     * @Description 获取当前类名包含有包名路径
     * @param @return 参数
     * @return String 返回类型
     * @throws
     */
    public static String getCurrentClassName(){
        return OkHttpClientUtil.class.getName();
    }
 
 
    /**
     * @Description    定义一个回调成功的接口.
     * @ClassName  IOkHttpClientCallBack
     * @Copyright (c) All Rights Reserved, 2018.
     */
    public interface IOkHttpClientCallBack {
 
        void onSuccessful(String retBody);
 
        void onError();
    }
}