请求三方http工具

ops/2024/12/20 12:03:06/
http://www.w3.org/2000/svg" style="display: none;">

请求三方接口工具封装
实现逻辑:

  1. 发起请求,输入基本请求信息:请求地址,请求类型,请求参数,是否需要认证
  2. 工具自动为需要添加认证的请求添加认证,如果发现token快要过期或返回的错误编码为定义的认证失败code,则自动重新获取token重新请求
package com.xxx;import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import lombok.Data;import java.util.HashMap;
import java.util.Map;
import java.util.Objects;/*** GeneralRequest* 通用请求** @author cd* @date 2024/12/18 10:51*/
@Data
public class GeneralRequest {/*** 请求路径*/private String url;/*** 方法类型*/private Method method;/*** 请求头*/private Map<String, String> headers;/*** form表单类型参数*/private Map<String, Object> form;/*** 请求体body*/private String body;/*** 是否需要鉴权*/private Boolean needAuth;/*** http请求工具*/private HttpRequest httpRequest;public GeneralRequest(String url, Method method, Boolean needAuth) {this.url = url;this.method = method;this.form = new HashMap<>();this.headers = new HashMap<>();this.needAuth = Objects.equals(needAuth, true);this.httpRequest = HttpRequest.of(url).method(method);}public GeneralRequest body(String body) {this.body = body;this.httpRequest.body(body);return this;}public GeneralRequest form(Map<String, Object> form) {this.form = form;this.httpRequest.form(form);return this;}public GeneralRequest addHeader(String name, String value) {this.headers.put(name, value);this.httpRequest.header(name, value);return this;}public String getParameter() {if (StrUtil.isNotBlank(this.body)) {return this.body;}if (CollUtil.isNotEmpty(this.form)) {return JSON.toJSONString(this.form);}return "";}
}
package com.xxx;import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;import java.time.LocalDateTime;
import java.util.Map;/*** XxxHttpUtil** @author cd* @date 2024/12/18 13:46*/
@Slf4j
public class XxxHttpUtil {private TokenResponse cacheTokenResponse = null;/*** 获取token** @param refreshToken 刷新token* @return*/public TokenResponse getToken(boolean refreshToken) {TokenResponse tokenResponse = null;if (!refreshToken) {tokenResponse = this.cacheTokenResponse;}if (tokenResponse != null) {return tokenResponse;}//        模拟重新获取tokenBaseRes<TokenResponse> baseRes = executeFrom("http://localhost:8080/getToken", Method.GET, false, null, new TypeReference<>() {});tokenResponse = baseRes.getData();this.cacheTokenResponse = tokenResponse;return tokenResponse;}public String signRequest(GeneralRequest generalRequest, boolean refreshToken) {TokenResponse tokenResponse = null;if (generalRequest.getNeedAuth()) {tokenResponse = getToken(refreshToken);
//            判断token是否快过期if (LocalDateTime.now().plusSeconds(10).isAfter(tokenResponse.getExpiresTime())) {tokenResponse = getToken(true);}
//            添加认证请求头generalRequest.addHeader("Authorization", tokenResponse.getAccessToken());}HttpResponse httpResponse = generalRequest.getHttpRequest().execute();int httpResponseStatus = httpResponse.getStatus();boolean success = httpResponseStatus == HttpStatus.HTTP_OK;String result = null;if (success) {result = httpResponse.body();}log.info("接口调用记录,HttpStatusCode:{},请求是否成功:{},请求地址:{},参数:{},结果:{}",httpResponseStatus, success ? "成功" : "失败", generalRequest.getUrl(), generalRequest.getParameter(), result);return result;}public <R> R doAction(GeneralRequest generalRequest, TypeReference<R> type) {String result = signRequest(generalRequest, false);
//        按三方返回格式判断,一般返回有code、success、dataif (StrUtil.contains(result, "code")) {JSONObject jsonObject = JSON.parseObject(result);String code = jsonObject.getString("code");
//            200:成功if (StrUtil.equals(code, "200")) {return JSON.parseObject(result, type);}
//            200:鉴权失败
//            刷新token重试else if (StrUtil.equals(code, "500")) {result = signRequest(generalRequest, true);if (StrUtil.isNotBlank(result)) {return JSON.parseObject(result, type);}} else {return JSON.parseObject(result, type);}}return null;}public <R> R execute(String url, Method method, Boolean needAuth, String body, Map<String, Object> formParams, TypeReference<R> type) {GeneralRequest generalRequest = new GeneralRequest(url, method, needAuth);if (body != null) {generalRequest.body(body);}if (formParams != null) {generalRequest.form(formParams);}return doAction(generalRequest, type);}public <R> R executeJson(String url, Method method, String body, TypeReference<R> type) {return this.execute(url, method, true, body, null, type);}public <R> R executeJson(String url, Method method, Boolean needAuth, String body, TypeReference<R> type) {return this.execute(url, method, needAuth, body, null, type);}public <R> R executeFrom(String url, Method method, Boolean needAuth, Map<String, Object> formParams, TypeReference<R> type) {return this.execute(url, method, needAuth, null, formParams, type);}public <R> R executeFrom(String url, Method method, Map<String, Object> formParams, TypeReference<R> type) {return this.execute(url, method, true, null, formParams, type);}
}
package com.xxx;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.time.LocalDateTime;/*** TokenResponse** @author cd* @date 2024/12/18 13:50*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TokenResponse {/*** token*/private String accessToken;/*** 过期时间*/private LocalDateTime expiresTime;
}

http://www.ppmy.cn/ops/143482.html

相关文章

深入浅出Flink CEP丨如何通过Flink SQL作业动态更新Flink CEP作业

复杂事件处理&#xff08;CEP&#xff09;是一种对事件流进行分析的技术&#xff0c;它能够识别出数据流中的事件序列是否符合特定的模式&#xff0c;并允许用户对这些模式进行处理。Flink CEP 是 CEP 在 Apache Flink 中的具体实现&#xff0c;是 Apache Flink 的一个库&#…

python学opencv|读取图像(十六)修改HSV图像HSV值

【1】引言 前序学习进程中&#xff0c;我们已经掌握了对HSV通道和BGR通道的拆分和合并&#xff0c;并通过自由组合的形式&#xff0c;获得了和初始图像完全不一样的新图像&#xff0c;相关文章可以参考下述链接&#xff1a; python学opencv|读取图像&#xff08;十四&#xf…

Unity类银河战士恶魔城学习总结(P180 Enemy Shady 幽影)

教程源地址&#xff1a;https://www.udemy.com/course/2d-rpg-alexdev/ 本章节传造了一个会自爆的敌人暗影殉道者 Enemy_Shady.cs 功能与逻辑 状态机管理&#xff1a; 定义了多个状态&#xff08;如 idleState, moveState, deadState, stunnedState, battleState&#xff09;…

导致服务器数据包丢失的原因有哪些?

服务器出现数据包丢失的情况通常是在网络传输的过程中&#xff0c;服务器无法接收到数据来传输到目标设备中&#xff0c;从而导致数据包丢失的情况&#xff0c;这种现象会影响着网站的访问速度&#xff0c;严重的话会导致业务出现中断。 本文就来探讨一下导致服务器数据包丢失的…

用 Python 从零开始创建神经网络(十七):回归(Regression)

回归&#xff08;Regression&#xff09; 引言1. 线性激活&#xff08;Linear Activation&#xff09;2. 均方误差损失&#xff08;Mean Squared Error Loss&#xff09;3. 均方误差损失导数&#xff08;Mean Squared Error Loss Derivative&#xff09;4. 平均平方误差 (MSE) …

机器人阻抗和导纳控制的区别

一、阻抗和导纳的概念 1.1 阻抗控制&#xff08;Impedance Control&#xff09; 外环&#xff1a;位置控制环 目的&#xff1a;确保机器人末端执行器达到预定的位置。输入&#xff1a;期望的位置pdespdes​。输出&#xff1a;期望的力/扭矩FdesFdes​。控制逻辑&#xff1a;根据…

感知机收敛性定理证明

1. 问题描述 感知机收敛性定理假设&#xff1a; 存在一个参数向量 θ&#xff08;被归一化为单位向量&#xff0c;&#xff0c;以及一个正数 &#xff0c;使得对所有训练样本 满足&#xff1a; 这是线性可分的假设&#xff0c;意味着每个样本点与正确超平面之间有一个至少为的…

Linux复习1——导论

世界三大操作系统&#xff1a;Windows、UNIX、Linux UNIX简洁、开放、可移植、价格高昂、闭源 Linux继承UNIX的优点、免费、开源 Linux的诞生&#xff1a;1991年&#xff0c;芬兰的一名大学生Linus Torvalds开发了linux内核 #开源的优点&#xff1a; 低风险&#xff1a;开…