程序员的资源宝库

网站首页 > gitee 正文

通过Hutool 调用远程API接口(POST/GET)

sanyeah 2024-04-12 17:39:18 gitee 3 ℃ 0 评论

 

背景:需要调用第三方接口,开启某项任务,用Hutool代替了HttpClient 调用第三方接口,简单粗暴。

 

代码如下:

 1 import java.util.Date;
 2 import org.apache.commons.lang.time.DateFormatUtils;
 3 import cn.hutool.http.HttpRequest;
 4 import cn.hutool.http.HttpUtil;
 5 import cn.hutool.json.JSONObject;
 6 import cn.hutool.json.JSONUtil;
 7 import lombok.extern.slf4j.Slf4j;
 8 
 9 @Slf4j
10 public class HutoolUtil {
11     
12     public static void main(String[] args) {
13         HutoolUtil.testHutoolGet();
14     }
15     
16     public static void testHutoolGet() {
17         String getResult = HttpUtil
18                 .createGet("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15677386236")
19                 .execute()
20                 .charset("gbk")
21                 .body();
22         log.info("getResult:"+getResult);
23     }
24     public static void testHutoolPost(String cameraId) {
25         JSONObject jsonObject = JSONUtil.createObj();
26         jsonObject.put("cameraId", cameraId);
27         jsonObject.put("startTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
28         jsonObject.put("callback", "http://www.baidu.com");
29         String postResult = HttpRequest
30                 .post("http://localhost:8080/v1/platedetect/tasks")
31                 .header("Content-Type","application/json")
32                 .body(jsonObject)
33                 .execute()
34                 .body();
35         log.info("postResult:"+postResult);
36     }
37 
38 }

 

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表