hutool发送请求

get请求

String body = HttpUtil.createGet("www.baidu.com").execute().body();

post请求

构建表单POST请求

// 构建表单POST请求
HttpRequest request = HttpRequest.post(url)
        .header("Content-Type", "application/x-www-form-urlencoded") // 表单类型的Content-Type
        .form("key1", "value1")
        .form("key2", "value2");

构建body POST请求

// 构建body POST请求
 // 请求的URL
        String url = "http://example.com/api/post";

        // 构建POST请求
        HttpRequest request = HttpRequest.post(url)
                .header("Content-Type", "application/json") // 设置请求头
                .body("{\"key\":\"value\"}"); // 设置请求体,这里是一个JSON字符串

        // 发送请求,并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        System.out.println(response.body());

构建body POST请求,还可以用jsonObject 转换成String

 JSONObject jsonObject = new JSONObject();
                        jsonObject.put("profile_id",userProFileMap.get(authDTO.getUserId()));
                        jsonObject.put("timezone",authDTO.getTimezone());
                        jsonObject.put("officeCode",authDTO.getOfficeCode());
                        String result = HttpUtil.post(updateUpfUserTimezoneUrl, JSON.toJSONString(jsonObject));

put请求

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

public class HutoolPutExample {
    public static void main(String[] args) {
        // 请求的URL
        String url = "http://example.com/api/put";

        // 构建PUT请求
        HttpRequest request = HttpRequest.put(url)
                .header("Content-Type", "application/json") // 设置请求头
                .body("{\"key\":\"newValue\"}"); // 设置请求体,这里是一个JSON字符串

        // 发送请求,并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        System.out.println(response.body());
    }
}


// form的形式传递参数,可以放在url上
        // 构建PUT请求
        HttpRequest request = HttpRequest.put(url)
                .header("Content-Type", "application/json") // 设置请求头
                .form("key1", "value1") // 添加URL参数
                .form("key2", "value2") // 添加URL参数
                .body("{\"additionalKey\":\"additionalValue\"}"); // 设置请求体,这里是一个JSON字符串

        // 发送请求,并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        System.out.println(response.body());
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值