Java Spring使用hutool的HttpRequest发送请求的几种方式
作者:Yeast_东
文章介绍了Hutool库中用于发送HTTP请求的工具,包括添加依赖、发送GET和POST请求的方法,以及GET请求的不同参数传递方式,感兴趣的朋友跟随小编一起看看吧
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发送请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
