Java Hutool 依赖包:如何发送带请求头的 POST 请求
使用 Hutool 发送带请求头的 POST 请求,可以使用 HttpUtil 类的 post 方法,并通过 Header 对象设置请求头。
首先,确保已经添加了 Hutool 的依赖包。在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.7.5</version>
</dependency>
然后,可以使用以下代码发送带请求头的 POST 请求:
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
public class PostWithHeaderExample {
public static void main(String[] args) {
// 设置请求头
Header header = Header.create()
.set('Content-Type', 'application/json')
.set('Authorization', 'Bearer your_token');
// 发送 POST 请求
HttpResponse response = HttpUtil.createPost('http://example.com/api')
.body('{"key": "value"}')
.header(header)
.execute();
// 输出响应结果
String body = response.body();
System.out.println(body);
}
}
在上述代码中,我们首先创建了一个 Header 对象,并使用 set 方法设置了 Content-Type 和 Authorization 请求头。然后,使用 HttpUtil 的 createPost 方法创建了一个 POST 请求对象,并使用 body 方法设置请求体,header 方法设置请求头。最后,调用 execute 方法发送请求,并通过 response 对象获取响应结果。
注意替换代码中的 'http://example.com/api' 为实际的请求 URL,替换 'your_token' 为实际的授权令牌。根据实际情况,还可以根据需求设置其他的请求头。
原文地址: https://www.cveoy.top/t/topic/quEe 著作权归作者所有。请勿转载和采集!