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

相关推荐
2601_9669496511 分钟前
实时行情中的成交量 Volume 到底是什么?包含盘中撤单量吗?从交易数据语义到 QuantDash 实战解析
开发语言·人工智能·python·量化·quantdash·量化数据源
you鬰18 分钟前
datawhale--llm-algo-leetcode9️⃣ SFT Training Loop
python·datawhale
叫我:松哥25 分钟前
基于flask仿小米商城管理系统,使用flask开的一个商场网站
数据库·后端·python·flask
智购科技无人售货机工厂33 分钟前
2026自动售货机防拆机物理安全设计:从安全螺丝到结构互锁的工程实践~YH
android·网络·驱动开发·python·单片机·安全·云原生
2401_8685347840 分钟前
校园网规划与设计
python·pygame
小猴子爱上树44 分钟前
跨境电商AI批量图片翻译工具,视频字幕翻译免费试用
人工智能·python·音视频
zx_741484811 小时前
【Python入门】爬虫实战:Requests + XPath 从基础到实战
开发语言·爬虫·python
高洁011 小时前
Teacher Forcing技术解析
人工智能·python·深度学习·transformer·知识图谱
2601_962065251 小时前
从零创建一个 Django 项目
后端·python·django
溪语流沙1 小时前
【Python项目实战】虚拟环境与依赖管理:venv / pip / requirements.txt实操
开发语言·python·pip