Blame view

src/main/java/com/huaheng/common/utils/http/OkHttpUtils.java 11.6 KB
tongzhonghao authored
1
2
3
4
package com.huaheng.common.utils.http;


import com.google.gson.Gson;
tongzhonghao authored
5
import com.huaheng.common.utils.security.ShiroUtils;
tongzhonghao authored
6
7
8
9
10
11
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
12
import javax.validation.constraints.NotNull;
tongzhonghao authored
13
14
15
16
17
18
19
20
21
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp发送请求
22
 *
tongzhonghao authored
23
24
25
26
27
28
29
30
 * @author huaheng
 * @Date 2022-5-30
 */
public class OkHttpUtils {

    private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);

    /**
31
     * 最多重试次数
tongzhonghao authored
32
     */
33
34
35
36
37
38
39
    public final static int MAX_RENTRY_COUNT = 0;

    /**
     * 最大连接时间(秒)
     */
    public final static int CONNECTION_TIMEOUT = 5;
tongzhonghao authored
40
    /**
41
     * 最大读取时间(秒)
xumiao authored
42
     */
43
44
    public final static int READ_TIMEOUT = 10;
xumiao authored
45
    /**
46
     * 最大写入时间(秒)
xumiao authored
47
     */
48
49
    public final static int WRITE_TIMEOUT = 10;
xumiao authored
50
    /**
tongzhonghao authored
51
52
53
     * JSON格式
     */
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
54
tongzhonghao authored
55
56
57
    /**
     * OkHTTP线程池最大空闲线程数
     */
58
59
    public final static int MAX_IDLE_CONNECTIONS = 40;
tongzhonghao authored
60
    /**
61
     * OkHTTP线程池空闲线程存活时间(秒)
tongzhonghao authored
62
     */
63
    public final static long KEEP_ALIVE_DURATION = 60;
tongzhonghao authored
64
65
66
67
68
69
70
71

    private static final String CONTENT_TYPE = "Content-Type";


    /**
     * client
     * 配置重试
     */
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    /**
     * client
     * 配置重试
     */
    /**
     * 访问接口参数配置
     */
    private final static OkHttpClient HTTP_CLIENT =
            new OkHttpClient.Builder().connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS).readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).addInterceptor(new OkHttpUtils.OkhttpInterceptor(MAX_RENTRY_COUNT)) // 过滤器,设置最大重试次数
                    .retryOnConnectionFailure(false).connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.SECONDS)).build();
    //    private final static OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder().readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
//        .writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS).connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
//        .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES)).build();
tongzhonghao authored
86
87
88
89
90
91
    private static final Gson GSON = new Gson();

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
92
     *            //* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
tongzhonghao authored
93
94
     * @return 所代表远程资源的响应结果
     */
95
    public static String sendGet(String url, String param) {
tongzhonghao authored
96
        //headers  请求头
97
        Map<String, String> headers = new HashMap<>();
tongzhonghao authored
98
99
100
        //请求URI
        String urlNameString = url + "?" + param;
101
        Request.Builder builder = new Request.Builder();
tongzhonghao authored
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        buildHeader(builder, headers);

        Request request = builder.url(urlNameString).get().build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            if (response.isSuccessful() && Objects.nonNull(response.body())) {
                String result = response.body().string();
                log.info("执行get请求, url: {} 成功,返回数据: {}", url, result);
                return result;
            }
        } catch (IOException e) {
            log.error("执行get请求,url: {} 失败!", url, e);
        }
        return "";
    }
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
    //此方法是将参数以body形式发送post请求
    public static String bodyget(String strURL, String json, String warehouseCode) {
        ApiLog apiLog = null;
        // using above json body as a input to post API call
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        //headers  请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");// 设置接收数据的格式
        headers.put("Content-Type", "application/json");// 设置发送数据的格式
        Request.Builder builder = new Request.Builder();
        buildHeader(builder, headers);
//        Request request = builder.url(strURL).post(body).build();
        Response response = null;
        String result = null;

        //请求URI
        String urlNameString = strURL + "?" + json;
        Request request = builder.url(urlNameString).get().build();
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            apiLog = ApiLogAspect.initApiLog(request, json, warehouseCode);
            apiLog.setWarehouseCode(warehouseCode);
            if (Objects.nonNull(response.body())) {
                result = response.body().string();
                log.info("执行post请求,url: {}, header: {} ,参数: {} 成功,返回结果: {}", strURL, headers, json, result);
            }
        } catch (IOException e) {
            ApiLogAspect.setApiLogException(apiLog, e);
            log.error("执行post请求,url: {},参数: {} 失败!", strURL, json, e);
        } finally {
            ApiLogAspect.finishApiLog(apiLog, response, result);
        }
        return result;
    }
tongzhonghao authored
153
154
155
156
157

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
158
     *            // * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
tongzhonghao authored
159
160
     * @return 所代表远程资源的响应结果
     */
161
    public static String sendPost(String url, String param) {
tongzhonghao authored
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        FormBody.Builder builder = new FormBody.Builder();
        String urlNameString = url + "?" + param;
        FormBody body = builder.build();
        Request request = new Request
                .Builder()
                .url(urlNameString)
                .post(body)
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            //调用成功
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    //此方法是将参数以body形式发送post请求
185
    public static String bodypost(String strURL, String json, String warehouseCode) {
tongzhonghao authored
186
187
188
189
        ApiLog apiLog = null;
        // using above json body as a input to post API call
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        //headers  请求头
190
191
192
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");// 设置接收数据的格式
        headers.put("Content-Type", "application/json");// 设置发送数据的格式
tongzhonghao authored
193
194
195
196
        Request.Builder builder = new Request.Builder();
        buildHeader(builder, headers);
        Request request = builder.url(strURL).post(body).build();
        Response response = null;
197
        String result = null;
tongzhonghao authored
198
199
        try {
            response = HTTP_CLIENT.newCall(request).execute();
200
            apiLog = ApiLogAspect.initApiLog(request, json, warehouseCode);
xumiao authored
201
202
            apiLog.setWarehouseCode(warehouseCode);
            if (Objects.nonNull(response.body())) {
周鸿 authored
203
204
                result = response.body().string();
                log.info("执行post请求,url: {}, header: {} ,参数: {} 成功,返回结果: {}", strURL, headers, json, result);
205
206
            } else {
                result = response.body().string();
周鸿 authored
207
208
209
210
211
212
213
214
215
216
            }
        } catch (IOException e) {
            ApiLogAspect.setApiLogException(apiLog, e);
            log.error("执行post请求,url: {},参数: {} 失败!", strURL, json, e);
        } finally {
            ApiLogAspect.finishApiLog(apiLog, response, result);
        }
        return result;
    }
周鸿 authored
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
    public static String bodypost(String strURL, String json, String warehouseCode,String apiName) {
        ApiLog apiLog = null;
        // using above json body as a input to post API call
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        //headers  请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");// 设置接收数据的格式
        headers.put("Content-Type", "application/json");// 设置发送数据的格式
        Request.Builder builder = new Request.Builder();
        buildHeader(builder, headers);
        Request request = builder.url(strURL).post(body).build();
        Response response = null;
        String result = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            apiLog = ApiLogAspect.initApiLog(request, json, warehouseCode);
            apiLog.setWarehouseCode(warehouseCode);
            if (Objects.nonNull(response.body())) {
                result = response.body().string();
                log.info("执行post请求,url: {}, header: {} ,参数: {} 成功,返回结果: {}", strURL, headers, json, result);
            } else {
                result = response.body().string();
            }
        } catch (IOException e) {
            ApiLogAspect.setApiLogException(apiLog, e);
            log.error("执行post请求,url: {},参数: {} 失败!", strURL, json, e);
        } finally {
            apiLog.setApiName(apiName);
            ApiLogAspect.finishApiLog(apiLog, response, result);
        }
        return result;
    }
tongzhonghao authored
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

    /**
     * 设置请求头
     *
     * @param builder .
     * @param headers 请求头
     */
    private static void buildHeader(Request.Builder builder, Map<String, String> headers) {
        if (Objects.nonNull(headers) && headers.size() > 0) {
            headers.forEach((k, v) -> {
                if (Objects.nonNull(k) && Objects.nonNull(v)) {
                    builder.addHeader(k, v);
                }
            });
        }
    }

    /**
     * 支持嵌套泛型的post请求。
     * <pre>
     *   Type type = new TypeToken<Results<User>>() {}.getType();
     * <pre/>
     *
     * @param url     链接
     * @param json    请求json
     * @param type    嵌套泛型
     * @return 响应对象, 可进行强转。
     */
    public static <T> T post(String url, String json, Type type) {
tongzhonghao authored
279
        String result = bodypost(url, json, ShiroUtils.getWarehouseCode());
tongzhonghao authored
280
281
282
283
284
        if (Objects.nonNull(result) && Objects.nonNull(type)) {
            return GSON.fromJson(result, type);
        }
        return null;
    }
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

    public static class OkhttpInterceptor implements Interceptor {

        // 最大重试次数
        private int maxRentry;

        public OkhttpInterceptor(int maxRentry) {
            this.maxRentry = maxRentry;
        }

        /**
         * 递归 2次下发请求,如果仍然失败 则返回 null 但是 intercept must not return null. 返回 null 会报 IllegalStateException 异常
         */
        public Response intercept(@NotNull Chain chain) throws IOException {
            return retry(chain, 0);
        }

        private Response retry(Chain chain, int retryCent) throws IOException {
            Request request = chain.request();
            Response response = null;
            try {
                response = chain.proceed(request);
            } catch (Exception e) {
                if (maxRentry > retryCent) {
                    return retry(chain, retryCent + 1);
                }
                if (Objects.isNull(response)) {
                    throw e;
                }
            }
            return response;
        }
    }
tongzhonghao authored
318
}