hutool为我们封装了发送请求的工具,我们一起来看看常用的有哪些吧!
1.添加依赖
<dependency>
<groupid>cn.hutool</groupid>
<artifactid>hutool-all</artifactid>
<version>5.8.11</version> <!-- 请使用最新版本 -->
</dependency>2.发送get请求
2.1 直接url传参
import cn.hutool.http.httputil;
import cn.hutool.core.util.strutil;
public class httpgetexample {
public static void main(string[] args) {
// 定义基础 url 和路径
string baseurl = "http://example.com";
string path = "/api/test";
// 定义参数
string name = "zhangsan";
int age = 21;
// 构建完整的 url
string url = strutil.format("{}/{}?name={}&age={}", baseurl, path, name, age);
// 发送 get 请求
string result = httputil.get(url);
// 输出响应结果
system.out.println("response: " + result);
}
}2.2 map传参
import cn.hutool.http.httputil;
import java.util.hashmap;
import java.util.map;
public class httpgetexample {
public static void main(string[] args) {
// 定义基础 url 和路径
string baseurl = "http://example.com";
string path = "/api/test";
// 构建完整的 url
string url = baseurl + path;
// 定义参数
map<string, object> params = new hashmap<>();
params.put("name", "aa");
params.put("age", 21);
// 发送 get 请求
string result = httputil.get(url, params);
// 输出响应结果
system.out.println("response: " + result);
}
}2.3 form传参
import cn.hutool.http.httprequest;
import cn.hutool.http.httputil;
import java.util.hashmap;
import java.util.map;
public class httpgetexample {
public static void main(string[] args) {
// 定义基础 url 和路径
string baseurl = "http://example.com";
string path = "/api/test";
// 构建完整的 url
string url = baseurl + path;
// 定义参数
map<string, object> params = new hashmap<>();
params.put("name", "aa");
params.put("age", 21);
// 发送 get 请求
string result = httprequest.get(url)
.form(params)
.execute()
.body();
// 输出响应结果
system.out.println("response: " + result);
}
}3. 发送post请求
3.1 json传参
public static void main(string[] args) {
// 定义基础 url 和路径
string baseurl = "http://example.com";
string path = "/api/test";
// 构建完整的 url
string url = baseurl + path;
// 定义参数
string jsonstring = "{\"token\":\"1234567890\",\"userid\":\"user123\",\"username\":\"张三\"}";
// 发送 get 请求
string result = httprequest.post(url)
.header("access-token", token) // 如果需要
.header("content-type","application/json")
.body(jsonstring)
.execute()
.body();
// 输出响应结果
system.out.println("response: " + result);
}3.2 form传参
public static void main(string[] args) {
// 定义基础 url 和路径
string baseurl = "http://example.com";
string path = "/api/test";
// 构建完整的 url
string url = baseurl + path;
// 定义参数
map<string, object> params = new hashmap<>();
params.put("name", "aa");
params.put("age", 21);
// 发送 get 请求
string result = httprequest.post(url)
.header("content-type","multipart/form-data;charset=utf-8")
.form(params)
.execute()
.body();
// 输出响应结果
system.out.println("response: " + result);
}到此这篇关于java spring使用hutool的httprequest发送请求的几种方式的文章就介绍到这了,更多相关java hutool httprequest发送请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论