当前位置: 首页 > news >正文

Java后端通过hutool接口发请求

hutool工具类发请求
Post请求单个参数
  @RequestMapping(value = "/test",method = RequestMethod.POST)APIResult<Void> test(@RequestBody(required = true) JSONObject params);

这里要注意三个点,一个是要用Post请求,一个是要用@RequestBody注解,最后一个是要用JSONObject对象接收

  @Overridepublic APIResult<Void> test(JSONObject params) {APIResult<Void> result = new APIResult<>();try {String taskId = params.getString("taskId");String url= "xxxx/task/test";String data = HttpUtil.post(url, JSONUtil.toJsonStr(params));System.out.println("请求结果:"+data);JSONObject rsObj = JSONObject.parseObject(data);if (rsObj.getInteger("code") != 0) {throw new RuntimeException("失败");}result.setMessage("成功");}catch (Exception e) {setExceptionResult(result, StateEnum.ERROR.getCode(), StateEnum.ERROR.getText(), e);}return result;}
发Post请求(带请求头)
// 坐标转换 wgs84转cgc2000
String url = "http://127.0.0.1:8000/test";
Map<String, Object> params = new HashMap<>();
params.put("from", "4326");
params.put("to", "4547");
params.put("lng", "114.21631738822728");
params.put("lat", "23.110115851089052");// 创建请求头
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
// 如果有其他头部信息可以继续添加headers.put("Authorization", "Basic xxx");// 发送GET请求并获取响应
HttpResponse response = HttpRequest.post(url).headerMap(headers, true) // 添加请求头.form(params)             // 设置表单参数.execute();// 获取响应体
String result = response.body();
if (result == null || result.isEmpty()) {throw new RuntimeException("坐标转换 wgs84转cgc2000失败");
}// 解析响应体
JSONObject resultJson = (JSONObject) JSONObject.parse(result);
JSONObject data = resultJson.getJSONObject("data");System.out.println(data); // 打印结果
发Get请求
@Override
public APIResult<String> originalCloudDisk(String fileUrl) {if (StringUtil.isEmpty(fileUrl)){throw new RuntimeException("文件目录fileUrl不能为空!");}String url= AppUtil.getProperty("cloudBaseUrl")+"/getSortieFiles?fileUrl="+fileUrl;String result = HttpUtil.get(url);System.out.println("请求结果:"+result);JSONObject rsObj = JSONObject.parseObject(result);if (rsObj.getInteger("state") != 200) {throw new RuntimeException("失败");}return null;
}
发Post请求(不带请求头)
// 跨系统同步任务状态【服务对接】
JSONObject reqParams = new JSONObject();
reqParams.put("taskType", 2);
JSONArray dataArray = new JSONArray();
JSONObject itemData = new JSONObject();
itemData.put("id", bizEntity.getId());
itemData.put("status", "d1");
dataArray.add(itemData);
reqParams.put("dataList", dataArray);System.out.println("请求参数:" + JSONUtil.toJsonStr(reqParams));
String url = ConfigUtil.getProperty("remoteServiceBaseUrl") + "/api/v1/sync/status";
String response = HttpUtil.post(url, JSONUtil.toJsonStr(reqParams));
System.out.println("响应结果:" + response);JSONObject resultObj = JSONObject.parseObject(response);
if (resultObj.getInteger("code") != 200) {throw new RuntimeException("状态同步失败");
}
使用JSONArray和JSONObject封装参数

在调用其他服务的外部接口的时候,经常需要封装参数去发请求,有时候不想每次都创建一个对应的VO对象去发请求的话,可以使用JSONArray和JSONObject封装参数

// 跨系统同步任务状态【服务对接】
JSONObject reqParams = new JSONObject();
reqParams.put("taskType", 2);
JSONArray dataArray = new JSONArray();
JSONObject itemData = new JSONObject();
itemData.put("id", bizEntity.getId());
itemData.put("status", "d1");
dataArray.add(itemData);
reqParams.put("dataList", dataArray);System.out.println("请求参数:" + JSONUtil.toJsonStr(reqParams));
String url = ConfigUtil.getProperty("remoteServiceBaseUrl") + "/api/v1/sync/status";
String response = HttpUtil.post(url, JSONUtil.toJsonStr(reqParams));
System.out.println("响应结果:" + response);JSONObject resultObj = JSONObject.parseObject(response);
if (resultObj.getInteger("code") != 200) {throw new RuntimeException("状态同步失败");
}
Feign接口发get请求【多参数】
/*** user组织中心*/
@FeignClient(name = "jpaas-user")
public interface UserClient {/*** 根据部门id查询部门负责人* @param params* @return*/@GetMapping({"/user/org/test"})JSONObject getPrincipalDeptById(@RequestParam Map<String, Object> params);
}
  /*** 根据部门id查询部门负责人* @param groupId* @return*/public String getPrincipalDeptById(String groupId) {Map<String, Object> params = new HashMap<>();params.put("groupId", groupId);params.put("relTypeId", 2);params.put("pageNum", 1);params.put("pageSize", 1);JSONObject result = userClient.getPrincipalDeptById(params);if ((int)result.get("code") == 0){JSONArray array = result.getJSONArray("data");if (array.size()>0){return array.getJSONObject(0).getString("p");}}return null;}

骚戴理解:get发请求的时候有多个参数,可以封装成一个map传递过去,要加上@RequestParam注解

后端封装复杂的Json参数

这个是前端传给后端的复杂Json参数,那么在后端应该怎么去封装这个参数呢?

{"userIds": ["U1001","U1002","U1003"],"contacts": ["13800001111","13900002222"],"msgType": "textcard","content": {"title": "活动处理提醒","description": "<div class=\"normal\">您有一项活动待处理:</div><div class=\"normal\">活动主题:系统升级说明会</div><div class=\"normal\">组织部门:技术部</div><div class=\"normal\">活动时间:2024-07-20 09:30:00至2024-07-20 11:30:00</div><div class=\"normal\">活动地点:三楼会议室</div><div class=\"blank-line\"></div><div class=\"normal\">点击此处进行快捷处理→</div>","url": "https://service.example.com/handle?activityId=A20240720"}
}

通过constructionParameter方法来封装上面复杂的Json参数

private JSONObject buildRequestParams(List<BusinessParticipant> participantList, String businessId) {JSONObject param = new JSONObject();ArrayList<String> userIds = new ArrayList<>();ArrayList<String> contacts = new ArrayList<>();BusinessMain business = businessMainMapper.selectById(businessId);// 组织信息转换String orgInfo = getOrgInfo(business.getOrgId());// 地点信息转换String locationInfo = getLocationInfo(business.getLocation());String content = "<div class=\"normal\">您有一项活动待处理:</div>" +"<div class=\"normal\">活动主题:" + business.getSubject() + "</div>" +"<div class=\"normal\">组织部门:" + orgInfo + "</div>" +"<div class=\"normal\">活动时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(business.getStartTime()) + "至" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(business.getEndTime()) + "</div>" +"<div class=\"normal\">活动地点:" + locationInfo + "</div>" +"<div class=\"blank-line\"></div>\n" +"<div class=\"normal\">点击此处进行快捷处理→</div>";String linkUrl = "https://xxx.xxx.com";// 封装目标用户标识for (BusinessParticipant participant : participantList) {if ("1".equals(participant.getSpecFlag())) {if (StringUtils.isNotEmpty(participant.getUserId())) {userIds.add(participant.getUserId());} else {contacts.add(participant.getContactInfo());}}}param.put("userIds", userIds);param.put("contacts", contacts);param.put("msgType", "textcard");JSONObject contentObj = new JSONObject();contentObj.put("title", "活动处理提醒");contentObj.put("description", content);contentObj.put("url", linkUrl);param.put("content", contentObj);return param;
}
调用第三方接口

很多时候会需要调用第三方系统提供的接口,通过在后端调用http方式来实现,需要注意的是调用第三方系统的接口应该是放在后端,而不是放在前端,这样更安全一些,后端发送http请求这里我是用的Hutool提供的工具类来实现的,需要考虑的是在后端怎么封装前端那种Json格式的参数,最后还需要注意在调用第三方接口的时候的BaseUrl值和一些固定的密钥值最好配在配置文件里面,便于后期的维护!

普通Json格式的传参方式

例如下面这种很常见的普通传参方式,例如在调用第三方接口的时候通常是需要先发请求去获取一个令牌,然后发请求的时候带上这个令牌,不然的话没有权限去调用这个接口,而往往获取令牌的请求格式就是下面这样的

{"access": "Xs","tokene": "bearer"
}
HashMap<String, Object> tokenParams = new HashMap();
tokenParams.put("access","Xs");
tokenParams.put("tokene","bearer"); 
//获取发请求所需的token令牌
HttpResponse httpResp = HttpRequest.post("/token") //url地址.form(tokenParams)//表单内容.timeout(20000)//超时,毫秒.execute();
if (httpResp.getStatus() == 200){//逻辑代码处理String tokenJson = httpResp.body();JSONObject jsonObject = JSON.parseObject(tokenJson);String token = (String) jsonObject.get("token");
}
复杂Json格式的传参方式

例如下面这种json又有数组,json里面又有json的复杂的,前端传json格式,后端用JSONObject接收

{"userIds": ["14165461653"],"mobiles": ["123456789"],"msgType": "textcard","content": {"title": "测试","description": "<div class=\"highlight\"> <div class=\"highlight\">您有一场培训待报名:</div><div class=\"highlight\">培训主题:提醒</div><div class=\"highlight\">组织培训科室:察组</div><div class=\"highlight\">培训时间:2023-11-21 11:59至2023-11-24 11:59</div><div class=\"highlight\">培训地点:提醒</div><hr><div class=\"highlight\">点击快捷完成报名-></div></div >","url": "完整的url地址"}
}

这里和上面的区别就在于这里是把JSONObject的param参数转成字符串,然后放在body里面传参的,并且指定格式为json字符串的格式application/json;charset=UTF-8,而上面的是封装成一个map然后放到form里面传参的

HttpResponse httpResponse = HttpRequest.post("/sendMsg").header("Authorization", "Bearer " + token) //令牌.body(param.toJSONString(),"application/json;charset=UTF-8")//表单内容.timeout(20000)//超时,毫秒.execute();if (httpResponse.getStatus() == 200){//逻辑代码处理String tokenJson = httpResponse.body();JSONObject jsonObject = JSON.parseObject(tokenJson);}
http://www.dtcms.com/a/299183.html

相关文章:

  • 【LeetCode刷题指南】--队列实现栈,栈实现队列
  • DocC的简单使用
  • VisionPro系列讲解 - 03 Simulator 模拟器使用
  • 【MySQL数据库备份与恢复2】备份的三种常用方法
  • 在C#中判断两个列表数据是否相同
  • 前缀和-238-除自身以外数组的乘积-力扣(LeetCode)
  • 数学建模国赛历年赛题与优秀论文学习思路
  • 弹性元空间:JEP 387 深度解析与架构演进
  • Windows Server存储池,虚拟磁盘在系统启动后不自动连接需要手动连接
  • Matrix Theory study notes[5]
  • Mybatis学习之配置文件(三)
  • 数学专业数字经济转型全景指南
  • 广东省省考备考(第五十七天7.26)——数量、言语(强化训练)
  • Linux c++ CMake常用操作
  • 提升网站性能:如何在 Nginx 中实现 Gzip 压缩和解压!
  • 广告业务中A/B实验分桶方法比较:UID VS DID
  • DIY心率监测:用ESP32和Max30102打造个人健康助手
  • Voxtral Mini:语音转文本工具,支持超长音频,多国语音
  • VMware Workstation17下安装Ubuntu20.04
  • Qt 线程池设计与实现
  • 面试150 只出现一次的数字
  • Pinia快速入门
  • 大模型面试回答,介绍项目
  • Flutter实现Retrofit风格的网络请求封装
  • Qt 线程同步机制:互斥锁、信号量等
  • VTK交互——ImageRegion
  • Mixture-of-Recursions: 混合递归模型,通过学习动态递归深度,以实现对自适应Token级计算的有效适配
  • RK3568笔记九十二:QT使用Opencv显示摄像头
  • 基于RK3588+国产实时系统的隧道掘进机智能操控终端应用
  • NOIP普及组|2009T1多项式输出