Hutool HTTP 操作教程

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 更加简洁,适合快速开发场景。

相关推荐
老白干27 分钟前
基于 Spring AOP 的操作日志记录:以 DeptController 增删接口为例
java·python·spring
John jj36 分钟前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索
aqi001 小时前
15天学会AI应用开发(十九)使用LangGraph实现持久记忆功能
人工智能·python·大模型·ai编程·ai应用
月光船幽幽1 小时前
KDTree查表实现观测到动作的统计映射
python
2401_868534781 小时前
论信息系统安全保障规划与设计
python·django
微小冷1 小时前
Optiland近轴光学
python·光学仿真·optiland·几何光学·近轴光学·高斯光学
databook1 小时前
基于模型的重要性评分进行“特征排序”
python·机器学习·scikit-learn
码云骑士1 小时前
94-实战Prompt优化师Agent-迭代优化-效果评分-自动生成Few-Shot
python·prompt
从零开始学习人工智能2 小时前
PyTorch 踩坑:Input type \(Half\) and bias type \(float\) 类型不匹配终极解决方案
人工智能·pytorch·python