Hutool 是一个 Java 工具库,其 http 模块提供了简洁的 HTTP 客户端封装。以下是详细教程。
1. 引入依赖
XML
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.25</version>
</dependency>
2. GET 请求
2.1 简单 GET
java
// 请求网页内容
String content = HttpUtil.get("https://www.baidu.com");
System.out.println(content);
2.2 带参数的 GET
java
// 方式一:拼接参数
String url = "https://api.example.com/user?name=张三&age=25";
String result = HttpUtil.get(url);
// 方式二:使用 HashMap 传参
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("name", "张三");
paramMap.put("age", "25");
String result2 = HttpUtil.get("https://api.example.com/user", paramMap);
2.3 带请求头的 GET
java
String result = HttpRequest.get("https://api.example.com/user")
.header("Authorization", "Bearer token123")
.header("User-Agent", "Hutool")
.timeout(5000) // 超时时间(毫秒)
.execute()
.body();
3. POST 请求
3.1 POST 表单提交
java
// 表单参数
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("username", "test");
paramMap.put("password", "123456");
String result = HttpUtil.post("https://api.example.com/login", paramMap);
3.2 POST JSON 提交
java
// JSON 字符串
String json = "{\"username\":\"test\",\"password\":\"123456\"}";
String result = HttpRequest.post("https://api.example.com/login")
.body(json)
.contentType("application/json")
.execute()
.body();
3.3 POST 文件上传
java
// 上传文件
File file = new File("D:/test.txt");
String result = HttpRequest.post("https://api.example.com/upload")
.form("file", file)
.form("description", "测试文件")
.execute()
.body();
4. 其他 HTTP 方法
4.1 PUT 请求
java
String json = "{\"name\":\"新名字\"}";
String result = HttpRequest.put("https://api.example.com/user/1")
.body(json)
.contentType("application/json")
.execute()
.body();
4.2 DELETE 请求
java
String result = HttpRequest.delete("https://api.example.com/user/1")
.execute()
.body();
5. 处理响应
5.1 获取完整响应信息
java
HttpResponse response = HttpRequest.get("https://api.example.com/data")
.execute();
// 获取响应状态码
int status = response.getStatus();
// 获取响应头
String contentType = response.header("Content-Type");
// 获取响应体
String body = response.body();
// 获取响应体字节数组
byte[] bytes = response.bodyBytes();
5.2 解析 JSON 响应
java
String result = HttpUtil.get("https://api.example.com/user/1");
// 使用 Hutool 的 JSON 工具
JSONObject json = JSONUtil.parseObj(result);
String name = json.getStr("name");
Integer age = json.getInt("age");
6. 配置 HTTP 客户端
6.1 全局配置
java
// 设置全局超时时间(毫秒)
HttpGlobalConfig.setTimeout(10000);
// 设置全局读取超时
HttpGlobalConfig.setReadTimeout(5000);
6.2 请求级配置
java
String result = HttpRequest.get("https://api.example.com/data")
.timeout(3000) // 连接超时
.setReadTimeout(5000) // 读取超时
.disableCache() // 禁用缓存
.followRedirects(true) // 跟随重定向
.execute()
.body();
7. 代理设置
java
// 设置代理
HttpRequest request = HttpRequest.get("https://api.example.com/data")
.setHttpProxy("127.0.0.1", 8080);
// 带认证的代理
request.setHttpProxy("127.0.0.1", 8080, "username", "password");
8. 下载文件
java
// 下载文件到指定路径
String fileUrl = "https://example.com/file.zip";
String destPath = "D:/download/file.zip";
HttpUtil.downloadFile(fileUrl, destPath);
// 下载到文件对象
File destFile = new File("D:/download/file.zip");
HttpUtil.downloadFile(fileUrl, destFile);
9. 完整示例
java
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public class HttpDemo {
public static void main(String[] args) {
// GET 请求
String getResult = HttpUtil.get("https://httpbin.org/get");
System.out.println("GET结果: " + getResult);
// POST JSON 请求
JSONObject param = new JSONObject();
param.set("name", "张三");
param.set("age", 25);
HttpResponse response = HttpRequest.post("https://httpbin.org/post")
.body(param.toString())
.contentType("application/json")
.execute();
System.out.println("状态码: " + response.getStatus());
System.out.println("响应体: " + response.body());
}
}
10. 常见问题
10.1 SSL 证书问题
java
// 忽略 SSL 证书验证(仅测试环境使用)
HttpRequest.get("https://self-signed.badssl.com")
.setSSLProtocol("TLSv1.2")
.execute();
10.2 中文乱码解决
java
// 指定响应编码
String result = HttpUtil.get("https://example.com", CharsetUtil.CHARSET_UTF_8);
// 或者手动设置
String result2 = HttpRequest.get("https://example.com")
.charset(CharsetUtil.CHARSET_UTF_8)
.execute()
.body();
总结
| 场景 | 推荐方法 |
|---|---|
| 简单 GET/POST | HttpUtil.get() / HttpUtil.post() |
| 需要设置请求头/超时 | HttpRequest.get().execute() |
| 文件上传/下载 | HttpRequest.post().form() / HttpUtil.downloadFile() |
| 复杂请求 | 使用 HttpRequest 链式调用 |
Hutool 的 HTTP 模块相比原生 HttpClient 或 OkHttp 更加简洁,适合快速开发场景。