Hutool 工具包调用接口使用流程

发布于:2025-03-30 ⋅ 阅读:(40) ⋅ 点赞:(0)

Hutool 工具包调用接口使用是很常见的,多方接口调度,今天我们分析一下:

1、pom引用jar包

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-core</artifactId>
    <version>5.8.22</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-http</artifactId>
    <version>5.8.22</version>
</dependency>

2、基本测试

1)get

import cn.hutool.http.HttpUtil;

public class HttpTest {
    public static void main(String[] args) {
        String response = HttpUtil.get("https://www.example.com");
        System.out.println(response);
    }
}

2)post

import cn.hutool.http.HttpUtil;

public class HttpPostExample {
    
    public static String sendPostRequest(String url, Map<String, String> paramMap) {
        // 发送表单格式的 POST 请求(application/x-www-form-urlencoded)
        String response = HttpUtil.post(url, paramMap);
        
        // 输出结果(实际业务中可按需处理)
        System.out.println("响应状态码: " + HttpUtil.getHttpResponse(url).getStatus());
        System.out.println("响应内容: \n" + response);
        
        return response;
    }

    // 测试用例
    public static void main(String[] args) {
        String url = "https://httpbin.org/post";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("key1", "value1");
        paramMap.put("key2", "value2");
        
        sendPostRequest(url, paramMap);
    }
}

 HttpUtil.post() 默认发送 application/x-www-form-urlencoded 格式请求,直接适配 Map<String, String> 参数。

3)json格式

import cn.hutool.http.HttpRequest;

public class JsonPostExample {
    
    public static String sendJsonPost(String url, Map<String, Object> paramMap) {
        return HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(paramMap))  // 将 Map 转 JSON 字符串
                .contentType("application/json")     // 显式指定 JSON 类型
                .timeout(5000)                       // 自定义超时(毫秒)
                .execute()
                .body();
    }
}

3、代理配置

HttpRequest.post(url)
    .setHttpProxy("127.0.0.1", 7890)  // 设置代理
    .execute();

4、禁止证书验证

HttpRequest.post(url)
    .setSSLSocketFactory(new CustomSSLFactory())  // 自定义 SSL
    .execute();

5、springBoot 服务集成

1)客户端附带请求头

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class HutoolHttpClient {

    public static String sendPostWithHeaders(String url, Map<String, String> paramMap, String token) {
        // 创建POST请求并设置请求头
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + token)  // 身份验证头
                .header("X-Custom-Header", "HutoolDemo")     // 自定义头
             //   .header(Header.CONTENT_TYPE, "application/json")
                .form(paramMap)                              // 表单参数
                .timeout(5000)                               // 超时时间(ms)
                .execute();

        // 获取响应结果
        if (response.isOk()) {
            String body = response.body();
            System.out.println("响应成功: " + body);
            return body;
        } else {
            System.out.println("响应失败: " + response.getStatus());
            return null;
        }
    }

    // 测试用例
    public static void main(String[] args) {
        String url = "http://localhost:8080/api/post";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("username", "admin");
        paramMap.put("password", "123456");
        String token = "your_jwt_token_here";

        sendPostWithHeaders(url, paramMap, token);
    }
}

json参数

  public static Object doPost (String url, Map<String, String> paramMap, String token){
        //......delete
         String   s  = JSONObject.toJSONString(paramMap);
         HttpResponse response = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json")
              //  .header("frim", "5Zub6eR5oqA")
               // .header(Header.AUTHORIZATION, token)
                .body(s)
                .timeout(20000)//超时,毫秒
                .execute();
        String result = response.body();

        return result;
    }

 2)服务端接收

import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class PostController {

    @PostMapping("/post")
    public ResponseEntity<Map<String, Object>> handlePostRequest(
            @RequestHeader("Authorization") String authHeader,   // 获取请求头
            @RequestParam Map<String, String> params             // 获取表单参数
    ) {
        // 验证Token
        if (!authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(401).body(Map.of("error", "Invalid token format"));
        }

        String token = authHeader.substring(7);  // 提取实际token
        if (!"your_jwt_token_here".equals(token)) {
            return ResponseEntity.status(401).body(Map.of("error", "Invalid token"));
        }

        // 验证自定义头
        String customHeader = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader("X-Custom-Header");
        System.out.println("收到自定义头: " + customHeader);

        // 返回参数和验证结果
        return ResponseEntity.ok(Map.of(
                "status", "success",
                "params", params,
                "token_valid", true
        ));
    }
}

json接收

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public R delete(@RequestBody userDTO req){
        userInfoService.deleteBatchByIds(req);
        return R.ok();
    }

 

6、

7、

8、