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

相关推荐
曦月逸霜2 小时前
啥是RAG 它能干什么?
人工智能·python·机器学习
2301_769340673 小时前
如何在 Vuetify 中可靠捕获 Chip 关闭事件(包括键盘触发).txt
jvm·数据库·python
南 阳4 小时前
Python从入门到精通day66
开发语言·python
m0_596749095 小时前
JavaScript中手动实现一个new操作符的底层逻辑
jvm·数据库·python
DTAS尺寸公差分析软件5 小时前
DTAS3D v13.0 三维尺寸公差分析软件可申请试用
python·尺寸公差分析·三维公差分析·公差仿真软件·尺寸链计算
DTAS尺寸公差分析软件5 小时前
DTAS 3D公差分析软件最新版本介绍
python·3d·尺寸公差分析·尺寸链计算·尺寸工程·尺寸链校核软件·公差仿真分析
PieroPc5 小时前
CAMWATCH — 局域网摄像头监控系统 Fastapi + html
前端·python·html·fastapi·监控
IpdataCloud5 小时前
高并发场景下IP数据接口怎么选?从QPS到离线库的完整选型指南
网络·网络协议·tcp/ip
feasibility.5 小时前
反爬十层妖塔:现代爬虫攻防的立体战争
爬虫·python·科技·scrapy·rust·go·硬件
十八旬5 小时前
快速安装ClaudeCode完整指南
开发语言·windows·python·claude