OkHttpUtils.java
11.6 KB
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
package com.huaheng.common.utils.http;
import com.google.gson.Gson;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull;
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发送请求
*
* @author huaheng
* @Date 2022-5-30
*/
public class OkHttpUtils {
private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);
/**
* 最多重试次数
*/
public final static int MAX_RENTRY_COUNT = 0;
/**
* 最大连接时间(秒)
*/
public final static int CONNECTION_TIMEOUT = 5;
/**
* 最大读取时间(秒)
*/
public final static int READ_TIMEOUT = 10;
/**
* 最大写入时间(秒)
*/
public final static int WRITE_TIMEOUT = 10;
/**
* JSON格式
*/
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
/**
* OkHTTP线程池最大空闲线程数
*/
public final static int MAX_IDLE_CONNECTIONS = 40;
/**
* OkHTTP线程池空闲线程存活时间(秒)
*/
public final static long KEEP_ALIVE_DURATION = 60;
private static final String CONTENT_TYPE = "Content-Type";
/**
* client
* 配置重试
*/
/**
* 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();
private static final Gson GSON = new Gson();
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* //* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
//headers 请求头
Map<String, String> headers = new HashMap<>();
//请求URI
String urlNameString = url + "?" + param;
Request.Builder builder = new Request.Builder();
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 "";
}
//此方法是将参数以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;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* // * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
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请求
public static String bodypost(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;
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 {
ApiLogAspect.finishApiLog(apiLog, response, result);
}
return result;
}
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;
}
/**
* 设置请求头
*
* @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) {
String result = bodypost(url, json, ShiroUtils.getWarehouseCode());
if (Objects.nonNull(result) && Objects.nonNull(type)) {
return GSON.fromJson(result, type);
}
return null;
}
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;
}
}
}