个人封装使用,仅供参考
package com.tthk.inland.ticket.core.utils.https;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.tthk.framework.base.api.dto.CommonResult;
import com.tthk.inland.ticket.core.enums.result.ResulEnum;
import com.tthk.inland.ticket.core.enums.wechat.WeChatEnums;
import com.tthk.inland.ticket.core.utils.wechat.WeChatRobotUtils;
import com.xxl.job.core.context.XxlJobHelper;
import java.lang.reflect.Type;
/**
* @Description 请求状态通知工具类
* @date 2023/4/13_17:08
* @author Foam
*/
public class RequestStatusNotify {
/**
* @Description 封装返回结果
* @date 2023/4/13
**/
public static <T> CommonResult<T> requestStatusNotify(HttpRequest request,Class<? extends T> aClass,Type type){
final var execute = request.execute();
if(execute.getStatus() != 200){
XxlJobHelper.log("接口调用失败");
// 微信通知
WeChatRobotUtils.pushNotice("【"+execute.getStatus()+"】接口调用失败:"+request.getUrl(), WeChatEnums.WARN);
return CommonResult.error(ResulEnum.INTERFACE_FALT.getErrorCode());
}else {
T o = null;
if(aClass != null){
o = JSONObject.parseObject(execute.body(), aClass);
}
if(type != null){
o = JSONObject.parseObject(execute.body(), type);
}
XxlJobHelper.log(execute.getStatus()+"接口调用结果:"+JSONObject.toJSONString(o));
// 封装返回结果
return CommonResult.success(o);
}
}
public static <T> CommonResult<T> requestStatusNotify(HttpRequest request,Type type){
return requestStatusNotify(request,null,type);
}
public static <T> CommonResult<T> requestStatusNotify(HttpRequest request,Class<? extends T> aClass){
return requestStatusNotify(request,aClass,null);
}
}
使用方法
public static final String SPECIAL_PRICE_URL = APP_OPER_URL + "/AppOper/GetPrice";
public static CommonResult<B2CSpecialPriceVO> getB2CSpecialPrice(B2CSpecialPriceDTO b2CSpecialPriceDTO){
final var body = HttpRequest.get(SPECIAL_PRICE_URL).form(EntityUtils.entityToMap(b2CSpecialPriceDTO));
return RequestStatusNotify.requestStatusNotify(body, new TypeReference<CommonResult<B2CSpecialPriceVO>>(){}.getType());
}