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 PostRequestExample {
public static void main(String[] args) {
String url = "http://example.com/api/post";
String requestBody = "{ \"key\": \"value\" }";
// 创建 HttpRequest 对象
HttpRequest request = HttpRequest.post(url)
.header("Content-Type", "application/json") // 设置请求头
.header("Custom-Header", "HeaderValue") // 可以添加更多的头部
.body(requestBody);
// 发送 POST 请求
HttpResponse response = request.execute();
// 解析 JSON 响应
JSONObject jsonObject = JSONUtil.parseObj(response.body());
// 使用解析后的数据
System.out.println("Parsed JSON: " + jsonObject);
// 假设我们想获取名为 "data" 的字段
String data = jsonObject.getStr("data");
System.out.println("Data field: " + data);
}
}
PostRequestExample
最新推荐文章于 2025-05-02 21:14:58 发布