Commit 3eeb67f9515ba8dcc3e71924da19a41b53029118
1 parent
9c925c8b
Http工具类优化
Signed-off-by: TanYibin <5491541@qq.com>
Showing
7 changed files
with
163 additions
and
92 deletions
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/api/acs/controller/AcsController.java
1 | 1 | package org.jeecg.modules.wms.api.acs.controller; |
2 | 2 | |
3 | +import java.io.IOException; | |
3 | 4 | import java.util.Map; |
4 | 5 | |
5 | 6 | import javax.annotation.Resource; |
... | ... | @@ -9,12 +10,14 @@ import org.jeecg.common.api.vo.Result; |
9 | 10 | import org.jeecg.common.system.util.JwtUtil; |
10 | 11 | import org.jeecg.modules.wms.api.acs.entity.AcsStatus; |
11 | 12 | import org.jeecg.modules.wms.api.acs.service.IAcsService; |
13 | +import org.jeecg.modules.wms.config.address.service.IAddressService; | |
12 | 14 | import org.jeecg.modules.wms.framework.aspectj.PassApiAuthentication; |
13 | 15 | import org.jeecg.modules.wms.framework.aspectj.lang.annotation.ApiLogger; |
14 | 16 | import org.jeecg.modules.wms.framework.controller.HuahengBaseController; |
15 | 17 | import org.jeecg.modules.wms.task.agvTask.service.IAgvTaskService; |
16 | 18 | import org.jeecg.utils.StringUtils; |
17 | 19 | import org.jeecg.utils.constant.QuantityConstant; |
20 | +import org.jeecg.utils.http.OkHttpUtils; | |
18 | 21 | import org.springframework.transaction.annotation.Transactional; |
19 | 22 | import org.springframework.web.bind.annotation.PostMapping; |
20 | 23 | import org.springframework.web.bind.annotation.RequestBody; |
... | ... | @@ -22,6 +25,8 @@ import org.springframework.web.bind.annotation.RequestMapping; |
22 | 25 | import org.springframework.web.bind.annotation.ResponseBody; |
23 | 26 | import org.springframework.web.bind.annotation.RestController; |
24 | 27 | |
28 | +import com.alibaba.fastjson.JSON; | |
29 | + | |
25 | 30 | import io.swagger.annotations.ApiOperation; |
26 | 31 | |
27 | 32 | @RestController |
... | ... | @@ -30,15 +35,21 @@ public class AcsController extends HuahengBaseController { |
30 | 35 | |
31 | 36 | @Resource |
32 | 37 | private IAcsService acsService; |
38 | + | |
33 | 39 | @Resource |
34 | 40 | private IAgvTaskService agvTaskService; |
35 | 41 | |
42 | + @Resource | |
43 | + private IAddressService addressService; | |
44 | + | |
36 | 45 | // @PassApiAuthentication |
37 | - @ApiLogger(apiName = "API接口第三方Token校验测试", from = "TEST") | |
46 | +// @ApiLogger(apiName = "API接口第三方Token校验测试", from = "TEST") | |
38 | 47 | @ResponseBody |
39 | 48 | @PostMapping(value = "/testTokenCheck") |
40 | 49 | public Result<?> testTokenCheck(@RequestBody Map<String, String> paramMap, HttpServletRequest request) { |
41 | - return new Result<>(); | |
50 | + String url = "http://127.0.0.1:8080/wms/api/wms/acs/testTokenCheck"; | |
51 | + String body = OkHttpUtils.sendPostByJsonStr(url, JSON.toJSONString(paramMap)); | |
52 | + return Result.ok(body); | |
42 | 53 | } |
43 | 54 | |
44 | 55 | |
... | ... |
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/config/address/service/impl/AddressServiceImpl.java
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/framework/aspectj/ApiAuthenticationAspect.java
... | ... | @@ -23,9 +23,11 @@ import com.auth0.jwt.JWTVerifier; |
23 | 23 | import com.auth0.jwt.algorithms.Algorithm; |
24 | 24 | import com.auth0.jwt.exceptions.JWTVerificationException; |
25 | 25 | import com.auth0.jwt.interfaces.DecodedJWT; |
26 | +import com.baomidou.mybatisplus.extension.service.IService; | |
26 | 27 | |
27 | 28 | import cn.hutool.core.date.DatePattern; |
28 | 29 | import cn.hutool.core.date.DateUtil; |
30 | +import cn.hutool.core.util.StrUtil; | |
29 | 31 | import lombok.extern.slf4j.Slf4j; |
30 | 32 | |
31 | 33 | /** |
... | ... | @@ -68,12 +70,16 @@ public class ApiAuthenticationAspect { |
68 | 70 | ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); |
69 | 71 | HttpServletRequest request = attributes.getRequest(); |
70 | 72 | String token = request.getHeader("token"); |
73 | + if (token == null) { | |
74 | + log.error("header token is null"); | |
75 | + throw new JWTVerificationException("header token is null"); | |
76 | + } | |
71 | 77 | try { |
72 | 78 | Algorithm algorithm = Algorithm.RSA256(rsa256Key.getPublicKey(), rsa256Key.getPrivateKey()); |
73 | 79 | JWTVerifier verifier = JWT.require(algorithm).withIssuer(HuahengJwtUtil.HUAHENG_SYSTEM_ID).build(); |
74 | 80 | verifier.verify(token); |
75 | 81 | } catch (JWTVerificationException e) { |
76 | - log.error("TOKEN认证失败:{}", e.getMessage()); | |
82 | + log.error(e.getMessage()); | |
77 | 83 | throw e; |
78 | 84 | } |
79 | 85 | } |
... | ... |
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/framework/aspectj/ApiLogAspect.java
... | ... | @@ -27,6 +27,7 @@ import org.jeecg.modules.wms.config.address.service.IAddressService; |
27 | 27 | import org.jeecg.modules.wms.framework.aspectj.lang.annotation.ApiLogger; |
28 | 28 | import org.jeecg.modules.wms.monitor.apiLog.entity.ApiLog; |
29 | 29 | import org.jeecg.modules.wms.monitor.apiLog.service.IApiLogService; |
30 | +import org.jeecg.utils.HuahengJwtUtil; | |
30 | 31 | import org.jeecg.utils.ServletUtils; |
31 | 32 | import org.jeecg.utils.SpringUtils; |
32 | 33 | import org.jeecg.utils.StringUtils; |
... | ... | @@ -239,47 +240,47 @@ public class ApiLogAspect { |
239 | 240 | /** |
240 | 241 | * 记录WMS调用第三方系统接口的请求信息 |
241 | 242 | * 在OKHttpUtils.bodypost方法中直接调用本类static方法 |
243 | + * @param apiLog | |
242 | 244 | **/ |
243 | - public static ApiLog initApiLog(Request request, String body) { | |
244 | - ApiLog log = new ApiLog(); | |
245 | + public static void initApiLog(ApiLog apiLog, Request request, String body) { | |
245 | 246 | try { |
246 | - log.setApiMethod(request.method()); | |
247 | - log.setUrl(request.url().toString()); | |
248 | - log.setRequestTime(new Date()); | |
249 | - parseUrl(log, request.url().url()); | |
250 | - log.setRequestHeader(request.headers().toString()); | |
251 | - log.setRequestBody(body); | |
247 | + apiLog.setApiMethod(request.method()); | |
248 | + apiLog.setUrl(request.url().toString()); | |
249 | + apiLog.setRequestTime(new Date()); | |
250 | + parseUrl(apiLog, request.url().url()); | |
251 | + apiLog.setRequestHeader(request.headers().toString()); | |
252 | + apiLog.setRequestBody(body); | |
252 | 253 | } catch (Exception e) { |
253 | 254 | e.printStackTrace(); |
254 | 255 | } |
255 | - return log; | |
256 | 256 | } |
257 | 257 | |
258 | 258 | /** 记录响应头信息 **/ |
259 | - public static void finishApiLog(ApiLog log, Response response, String body) { | |
259 | + public static void finishApiLog(ApiLog log, Response response, String responseBody) { | |
260 | 260 | try { |
261 | - log.setResponseBody(body); | |
262 | 261 | log.setResponseTime(new Date()); |
263 | 262 | Long duration = log.getResponseTime().getTime() - log.getRequestTime().getTime(); |
264 | 263 | log.setDuration(duration.intValue()); |
264 | + if (response == null) { | |
265 | + return; | |
266 | + } | |
265 | 267 | log.setHttpCode(response.code()); |
266 | - | |
267 | - // 响应头 | |
268 | 268 | log.setResponseHeader(response.headers().toString()); |
269 | - Result ajaxResult = null; | |
269 | + log.setResponseBody(responseBody); | |
270 | + Result result = null; | |
270 | 271 | try { |
271 | - ajaxResult = JSON.parseObject(body, Result.class); | |
272 | + result = JSON.parseObject(responseBody, Result.class); | |
272 | 273 | } catch (Exception ex) { |
273 | - body = JSON.parse(body).toString(); | |
274 | - ajaxResult = JSON.parseObject(body, Result.class); | |
274 | + responseBody = JSON.parse(responseBody).toString(); | |
275 | + result = JSON.parseObject(responseBody, Result.class); | |
275 | 276 | } |
276 | - log.setRetCode(ajaxResult.getCode()); | |
277 | + log.setRetCode(result.getCode()); | |
277 | 278 | } catch (Exception e) { |
278 | 279 | e.printStackTrace(); |
279 | 280 | } finally { |
280 | 281 | try { |
281 | 282 | if (StringUtils.isNotEmpty(log.getResponseBody()) && log.getResponseBody().length() > 2001) { |
282 | - log.setResponseBody(log.getResponseBody().substring(0, 2000) + "...\nResponseBodyLength:" + log.getResponseBody().length()); | |
283 | + log.setResponseBody(log.getResponseBody().substring(0, 2000) + "...\n"); | |
283 | 284 | } |
284 | 285 | } catch (Exception e) { |
285 | 286 | e.printStackTrace(); |
... | ... | @@ -289,16 +290,16 @@ public class ApiLogAspect { |
289 | 290 | } |
290 | 291 | |
291 | 292 | /** 根据url,从address表中判断调用的去向 **/ |
292 | - public static void parseUrl(ApiLog log, URL url) { | |
293 | + public static void parseUrl(ApiLog apiLog, URL url) { | |
293 | 294 | try { |
294 | 295 | String[] spList = url.toString().split("/"); |
295 | 296 | String apiName = spList[spList.length - 1]; |
296 | 297 | String ip = JeecgSystemApplication.getLocalHostExactAddress().getHostAddress(); |
297 | 298 | Address address = addressService.getAddressByUrl(url.toString(), QuantityConstant.DEFAULT_WAREHOUSE); |
298 | - log.setApiName(apiName); | |
299 | - log.setRequestFrom("WMS"); | |
300 | - log.setIp(ip); | |
301 | - log.setResponseBy(address.getParam().toUpperCase()); | |
299 | + apiLog.setApiName(apiName); | |
300 | + apiLog.setRequestFrom(HuahengJwtUtil.HUAHENG_SYSTEM_ID); | |
301 | + apiLog.setIp(ip); | |
302 | + apiLog.setResponseBy(address.getParam().toUpperCase()); | |
302 | 303 | } catch (Exception e) { |
303 | 304 | e.printStackTrace(); |
304 | 305 | } |
... | ... | @@ -398,7 +399,7 @@ public class ApiLogAspect { |
398 | 399 | public static void setApiLogException(ApiLog log, Exception e) { |
399 | 400 | try { |
400 | 401 | String exception = ExceptionUtils.getFullStackTrace(e); |
401 | - String shortExpInfo = e.getMessage() + "\n" + org.apache.commons.lang3.StringUtils.left(exception, 1000); | |
402 | + String shortExpInfo = e.getMessage() + "\n" + org.apache.commons.lang3.StringUtils.left(exception, 1000) + "..."; | |
402 | 403 | log.setException(shortExpInfo); |
403 | 404 | } catch (Exception ex) { |
404 | 405 | ex.printStackTrace(); |
... | ... | @@ -408,7 +409,7 @@ public class ApiLogAspect { |
408 | 409 | public static void setApiLogThrowable(ApiLog log, Throwable e) { |
409 | 410 | try { |
410 | 411 | String exception = ExceptionUtils.getFullStackTrace(e); |
411 | - String shortExpInfo = e.getMessage() + "\n" + org.apache.commons.lang3.StringUtils.left(exception, 1000); | |
412 | + String shortExpInfo = e.getMessage() + "\n" + org.apache.commons.lang3.StringUtils.left(exception, 1000) + "..."; | |
412 | 413 | log.setException(shortExpInfo); |
413 | 414 | } catch (Exception ex) { |
414 | 415 | ex.printStackTrace(); |
... | ... |
huaheng-wms-core/src/main/java/org/jeecg/utils/HuahengJwtUtil.java
... | ... | @@ -28,7 +28,7 @@ public class HuahengJwtUtil { |
28 | 28 | /** token失效时间 1天 */ |
29 | 29 | public static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; |
30 | 30 | |
31 | - public static final String HUAHENG_SYSTEM_ID = "HUAHENG-WMS4-4.0.1"; | |
31 | + public static final String HUAHENG_SYSTEM_ID = "HUAHENG-WMS4"; | |
32 | 32 | |
33 | 33 | /** |
34 | 34 | * 根据request中的token获取用户账号 |
... | ... |
huaheng-wms-core/src/main/java/org/jeecg/utils/http/OkHttpUtils.java
... | ... | @@ -3,13 +3,18 @@ package org.jeecg.utils.http; |
3 | 3 | import com.alibaba.fastjson.JSON; |
4 | 4 | import com.alibaba.fastjson.TypeReference; |
5 | 5 | import com.alibaba.fastjson.parser.Feature; |
6 | +import com.aliyun.oss.ServiceException; | |
7 | +import com.xkcoding.http.util.StringUtil; | |
6 | 8 | |
9 | +import antlr.StringUtils; | |
10 | +import cn.hutool.core.util.StrUtil; | |
7 | 11 | import net.bytebuddy.asm.Advice.This; |
8 | 12 | import okhttp3.*; |
9 | 13 | import org.jeecg.modules.wms.framework.aspectj.ApiLogAspect; |
10 | 14 | import org.jeecg.modules.wms.monitor.apiLog.entity.ApiLog; |
11 | 15 | import org.slf4j.Logger; |
12 | 16 | import org.slf4j.LoggerFactory; |
17 | +import org.springframework.messaging.support.ErrorMessage; | |
13 | 18 | |
14 | 19 | import java.io.IOException; |
15 | 20 | import java.lang.reflect.Type; |
... | ... | @@ -17,6 +22,7 @@ import java.util.HashMap; |
17 | 22 | import java.util.Map; |
18 | 23 | import java.util.Objects; |
19 | 24 | import java.util.concurrent.TimeUnit; |
25 | +import java.util.concurrent.TimeoutException; | |
20 | 26 | |
21 | 27 | import javax.validation.constraints.NotNull; |
22 | 28 | |
... | ... | @@ -58,47 +64,62 @@ public class OkHttpUtils { |
58 | 64 | */ |
59 | 65 | public final static int MAX_IDLE_CONNECTIONS = 100; |
60 | 66 | /** |
61 | - * OkHTTP线程池空闲线程存活时间 | |
67 | + * OkHTTP线程池空闲线程存活时间(秒) | |
62 | 68 | */ |
63 | - public final static long KEEP_ALIVE_DURATION = 30L; | |
69 | + public final static long KEEP_ALIVE_DURATION = 60; | |
64 | 70 | |
65 | 71 | private static final String CONTENT_TYPE = "Content-Type"; |
66 | 72 | |
67 | - /** | |
68 | - * client 配置重试 | |
69 | - */ | |
73 | + /** 访问接口参数配置 */ | |
70 | 74 | private final static OkHttpClient HTTP_CLIENT = |
71 | 75 | new OkHttpClient.Builder().connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS).readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) |
72 | 76 | .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).addInterceptor(new OkHttpUtils.OkhttpInterceptor(MAX_RENTRY_COUNT)) // 过滤器,设置最大重试次数 |
73 | - .retryOnConnectionFailure(false).connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES)).build(); | |
77 | + .retryOnConnectionFailure(false).connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.SECONDS)).build(); | |
74 | 78 | |
75 | 79 | /** |
76 | 80 | * 向指定 URL 发送GET方法的请求 |
77 | - * @param url 发送请求的 URL //* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 | |
78 | - * @return 所代表远程资源的响应结果 | |
81 | + * @param url 发送请求的 URL | |
82 | + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式 | |
83 | + * @return 所代表远程资源的响应结果 | |
84 | + * @throws Exception | |
79 | 85 | */ |
80 | 86 | public static String sendGet(String url, String param) { |
81 | - ApiLog apiLog = null; | |
82 | - // headers 请求头 | |
83 | - Map<String, String> headers = new HashMap<>(); | |
84 | - // 请求URI | |
85 | - String urlNameString = url + "?" + param; | |
87 | + Map<String, String> headers = new HashMap<String, String>(); | |
88 | + return sendGet(url, headers, param); | |
89 | + } | |
90 | + | |
91 | + /** | |
92 | + * 向指定 URL 发送GET方法的请求 | |
93 | + * @param url 发送请求的 URL | |
94 | + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式 | |
95 | + * @param headers 请求头 | |
96 | + * @return 所代表远程资源的响应结果 | |
97 | + * @throws Exception | |
98 | + */ | |
99 | + public static String sendGet(String url, Map<String, String> headers, String param) { | |
100 | + ApiLog apiLog = new ApiLog(); | |
86 | 101 | Request.Builder builder = new Request.Builder(); |
87 | 102 | buildHeader(builder, headers); |
88 | - | |
89 | - Request request = builder.url(urlNameString).get().build(); | |
103 | + Request request = builder.url(url + "?" + param).get().build(); | |
90 | 104 | Response response = null; |
91 | 105 | String result = null; |
92 | 106 | try { |
93 | - apiLog = ApiLogAspect.initApiLog(request, param); | |
107 | + ApiLogAspect.initApiLog(apiLog, request, param); | |
94 | 108 | response = HTTP_CLIENT.newCall(request).execute(); |
95 | - if (response.isSuccessful() && Objects.nonNull(response.body())) { | |
109 | + if (response.isSuccessful() && Objects.nonNull(response.body())) {// 调用成功 | |
96 | 110 | result = response.body().string(); |
97 | - log.info("执行GET请求,url:{},header:{},param:{} 成功,返回结果:{}", url, JSON.toJSONString(headers), param, result); | |
111 | + log.info("执行GET请求成功,url:{},header:{},param:{},result:{}", url, JSON.toJSONString(headers), param, result); | |
112 | + } else { | |
113 | + String errorString = StrUtil.format("执行GET请求失败!url:{},header:{},param:{},responseCode:{},responseMessage:{}", url, JSON.toJSONString(headers), param, | |
114 | + response.code(), response.message()); | |
115 | + log.error(errorString); | |
116 | + throw new ServiceException(errorString); | |
98 | 117 | } |
99 | - } catch (IOException e) { | |
100 | - log.error("执行GET请求,url:{},header:{},param:{} 失败!", url, JSON.toJSONString(headers), param, e); | |
118 | + } catch (Exception e) { | |
119 | + String errorString = StrUtil.format("执行GET请求异常!url:{},header:{},param:{} {}", url, JSON.toJSONString(headers), param, e.getMessage()); | |
120 | + log.error(errorString, e); | |
101 | 121 | ApiLogAspect.setApiLogException(apiLog, e); |
122 | + throw new RuntimeException(errorString, e); | |
102 | 123 | } finally { |
103 | 124 | ApiLogAspect.finishApiLog(apiLog, response, result); |
104 | 125 | } |
... | ... | @@ -107,61 +128,93 @@ public class OkHttpUtils { |
107 | 128 | |
108 | 129 | /** |
109 | 130 | * 向指定 URL 发送POST方法的请求 |
110 | - * @param url 发送请求的 URL | |
111 | - * @param param 请求参数,请求参数是 name1=value1&name2=value2 的形式。 | |
112 | - * @return 远程资源的响应结果 | |
113 | - * @throws IOException | |
131 | + * @param url 发送请求的 URL | |
132 | + * @param param 请求参数,请求参数是 name1=value1&name2=value2 的形式 | |
133 | + * @return 远程资源的响应结果 | |
134 | + * @throws IOException | |
135 | + */ | |
136 | + public static String sendPost(String url, String param) throws IOException { | |
137 | + Map<String, String> headers = new HashMap<String, String>(); | |
138 | + return sendPost(url, headers, param); | |
139 | + } | |
140 | + | |
141 | + /** | |
142 | + * 向指定 URL 发送POST方法的请求 | |
143 | + * @param url 发送请求的 URL | |
144 | + * @param param 请求参数,请求参数是 name1=value1&name2=value2 的形式 | |
145 | + * @param headers 请求头 | |
146 | + * @return 远程资源的响应结果 | |
147 | + * @throws IOException | |
114 | 148 | */ |
115 | - public static String sendPost(String url, String param) { | |
116 | - ApiLog apiLog = null; | |
117 | - FormBody.Builder builder = new FormBody.Builder(); | |
118 | - String urlNameString = url + "?" + param; | |
119 | - FormBody body = builder.build(); | |
120 | - Request request = new Request.Builder().url(urlNameString).post(body).build(); | |
149 | + public static String sendPost(String url, Map<String, String> headers, String param) { | |
150 | + ApiLog apiLog = new ApiLog(); | |
151 | + Request.Builder builder = new Request.Builder(); | |
152 | + buildHeader(builder, headers); | |
153 | + FormBody body = new FormBody.Builder().build(); | |
154 | + Request request = builder.url(url + "?" + param).post(body).build(); | |
121 | 155 | Response response = null; |
122 | 156 | String result = null; |
123 | 157 | try { |
124 | - apiLog = ApiLogAspect.initApiLog(request, param); | |
158 | + ApiLogAspect.initApiLog(apiLog, request, param); | |
125 | 159 | response = HTTP_CLIENT.newCall(request).execute(); |
126 | - // 调用成功 | |
127 | - if (response.isSuccessful() && response.body() != null) { | |
160 | + if (response.isSuccessful() && Objects.nonNull(response.body())) {// 调用成功 | |
128 | 161 | result = response.body().string(); |
129 | - log.info("执行GET请求,url:{},param:{} 成功,返回结果:{}", url, param, result); | |
162 | + log.info("执行POST请求成功,url:{},header:{},param:{},result:{}", url, JSON.toJSONString(headers), param, result); | |
163 | + } else { | |
164 | + String errorString = StrUtil.format("执行POST请求失败!url:{},header:{},param:{},responseCode:{},responseMessage:{}", url, JSON.toJSONString(headers), | |
165 | + param, response.code(), response.message()); | |
166 | + log.error(errorString); | |
167 | + throw new ServiceException(errorString); | |
130 | 168 | } |
131 | - } catch (IOException e) { | |
132 | - log.error("执行GET请求,url:{},param:{} 失败!", url, param, e); | |
169 | + } catch (Exception e) { | |
170 | + String errorString = StrUtil.format("执行POST请求异常!url:{},header:{},param:{} {}", url, JSON.toJSONString(headers), param, e.getMessage()); | |
171 | + log.error(errorString, e); | |
133 | 172 | ApiLogAspect.setApiLogException(apiLog, e); |
173 | + throw new RuntimeException(errorString, e); | |
134 | 174 | } finally { |
135 | 175 | ApiLogAspect.finishApiLog(apiLog, response, result); |
136 | 176 | } |
137 | 177 | return result; |
138 | 178 | } |
139 | 179 | |
140 | - /** JSONString形式发送POST请求 | |
141 | - * @throws IOException */ | |
142 | - public static String sendPostByJsonStr(String url, String json) { | |
143 | - ApiLog apiLog = null; | |
144 | - // using above json body as a input to post API call | |
145 | - RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json); | |
146 | - // headers 请求头 | |
147 | - Map<String, String> headers = new HashMap<>(); | |
180 | + public static String sendPostByJsonStr(String url, String jsonString) { | |
181 | + Map<String, String> headers = new HashMap<String, String>(); | |
182 | + return sendPostByJsonStr(url, headers, jsonString); | |
183 | + } | |
184 | + | |
185 | + /** | |
186 | + * JSONString形式发送POST请求 | |
187 | + * @throws Exception | |
188 | + * @throws IOException | |
189 | + */ | |
190 | + public static String sendPostByJsonStr(String url, Map<String, String> headers, String jsonString) { | |
191 | + ApiLog apiLog = new ApiLog(); | |
148 | 192 | headers.put("Accept", "application/json");// 设置接收数据的格式 |
149 | 193 | headers.put("Content-Type", "application/json");// 设置发送数据的格式 |
150 | 194 | Request.Builder builder = new Request.Builder(); |
151 | 195 | buildHeader(builder, headers); |
196 | + // using above json body as a input to post API call | |
197 | + RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, jsonString); | |
152 | 198 | Request request = builder.url(url).post(body).build(); |
153 | 199 | Response response = null; |
154 | 200 | String result = null; |
155 | 201 | try { |
156 | - apiLog = ApiLogAspect.initApiLog(request, json); | |
202 | + ApiLogAspect.initApiLog(apiLog, request, jsonString); | |
157 | 203 | response = HTTP_CLIENT.newCall(request).execute(); |
158 | - if (response.isSuccessful() && Objects.nonNull(response.body())) { | |
204 | + if (response.isSuccessful() && Objects.nonNull(response.body())) {// 调用成功 | |
159 | 205 | result = response.body().string(); |
160 | - log.info("执行POST请求,url:{},header:{},param:{} 成功,返回结果:{}", url, JSON.toJSONString(headers), json, result); | |
206 | + log.info("执行POST请求成功,url:{},header:{},param:{},result:{}", url, JSON.toJSONString(headers), jsonString, result); | |
207 | + } else { | |
208 | + String errorString = StrUtil.format("执行POST请求失败!url:{},header:{},param:{},responseCode:{},responseMessage:{}", url, JSON.toJSONString(headers), | |
209 | + jsonString, response.code(), response.message()); | |
210 | + log.error(errorString); | |
211 | + throw new ServiceException(errorString); | |
161 | 212 | } |
162 | - } catch (IOException e) { | |
163 | - log.error("执行POST请求,url:{},header:{},param:{} 失败!", url, JSON.toJSONString(headers), json, e); | |
213 | + } catch (Exception e) { | |
214 | + String errorString = StrUtil.format("执行POST请求异常!url:{},header:{},param:{} {}", url, JSON.toJSONString(headers), jsonString, e.getMessage()); | |
215 | + log.error(errorString, e); | |
164 | 216 | ApiLogAspect.setApiLogException(apiLog, e); |
217 | + throw new RuntimeException(errorString, e); | |
165 | 218 | } finally { |
166 | 219 | ApiLogAspect.finishApiLog(apiLog, response, result); |
167 | 220 | } |
... | ... | @@ -185,13 +238,13 @@ public class OkHttpUtils { |
185 | 238 | |
186 | 239 | /** |
187 | 240 | * 支持嵌套泛型的POST请求 |
188 | - * @param url 链接 | |
189 | - * @param json 请求json | |
190 | - * @param type 嵌套泛型 | |
191 | - * @return 响应对象, 可进行强转。 | |
192 | - * @throws IOException | |
241 | + * @param url 链接 | |
242 | + * @param json 请求json | |
243 | + * @param type 嵌套泛型 | |
244 | + * @return 响应对象, 可进行强转。 | |
245 | + * @throws Exception | |
193 | 246 | */ |
194 | - public static <T> T sendPostByJsonStr(String url, String jsonString, TypeReference<T> type) throws IOException { | |
247 | + public static <T> T sendPostByJsonStr(String url, String jsonString, TypeReference<T> type) throws Exception { | |
195 | 248 | String result = sendPostByJsonStr(url, jsonString); |
196 | 249 | if (Objects.nonNull(result) && Objects.nonNull(type)) { |
197 | 250 | return JSON.parseObject(result, type); |
... | ... | @@ -207,16 +260,14 @@ public class OkHttpUtils { |
207 | 260 | this.maxRentry = maxRentry; |
208 | 261 | } |
209 | 262 | |
210 | - @NotNull | |
211 | - @Override | |
212 | 263 | public Response intercept(@NotNull Chain chain) throws IOException { |
213 | 264 | /* |
214 | - * 递归 2次下发请求,如果仍然失败 则返回 null ,但是 intercept must not return null. 返回 null 会报 IllegalStateException 异常 | |
265 | + * 递归 2次下发请求,如果仍然失败 则返回 null 但是 intercept must not return null. 返回 null 会报 IllegalStateException 异常 | |
215 | 266 | */ |
216 | 267 | return retry(chain, 0); |
217 | 268 | } |
218 | 269 | |
219 | - private Response retry(Chain chain, int retryCent) { | |
270 | + private Response retry(Chain chain, int retryCent) throws IOException { | |
220 | 271 | Request request = chain.request(); |
221 | 272 | Response response = null; |
222 | 273 | try { |
... | ... | @@ -225,6 +276,9 @@ public class OkHttpUtils { |
225 | 276 | if (maxRentry > retryCent) { |
226 | 277 | return retry(chain, retryCent + 1); |
227 | 278 | } |
279 | + if (Objects.isNull(response)) { | |
280 | + throw e; | |
281 | + } | |
228 | 282 | } |
229 | 283 | return response; |
230 | 284 | } |
... | ... |