hutool为我们封装了发送请求的工具,我们一起来看看常用的有哪些吧!
1.添加依赖
cn.hutoolhutool-all5.8.11
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 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 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 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发送请求内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
