提示:今天主要学习了使用Hutool的方式来发送Http请求
文章目录
目录
文章目录
一、导库
二、使用
三、调用
四、结果
一、导库
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.26</version>
</dependency>
二、使用
package com.yupi.yuapiinterface.client;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.yuapiinterface.model.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.HashMap;
/**
* 调用第三方接口的客户端
*
* @create 2023/09/06 23:06
* @Author xinggui
*/
public class YuApiClient {
public String getNameByGet(String name) {
//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("name", name);
String result3= HttpUtil.get("http://localhost:8123/api/name/", paramMap);
System.out.println(result3);
return result3;
}
public String getNameByPost(@RequestParam String name) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("name", name);
String result= HttpUtil.post("http://localhost:8123/api/name/", paramMap);
System.out.println(result);
return result;
}
public String getUserNameByPost(@RequestBody User user) {
String json = JSONUtil.toJsonStr(user);
HttpResponse httpResponse = HttpRequest.post("http://localhost:8123/api/name/user").body(json).execute();
System.out.println(httpResponse.getStatus());
String result = httpResponse.body();
return result;
}
}
三、调用
YuApiClient yuApiClient = new YuApiClient();
String result = yuApiClient.getNameByGet("贺浩浩");
String result1 = yuApiClient.getNameByPost("星轨");
User user = new User();
user.setUsername("星轨xxx");
String result2 = yuApiClient.getUserNameByPost(user);
System.out.println(result);
System.out.println(result1);
System.out.println(result2);