You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spring新RestClient时如何给GET请求添加请求体?

使用Spring RestClient发送带请求体的GET请求

RestClient的快捷方法(比如.get())确实没有提供设置请求体的入口——这是因为HTTP规范不推荐GET请求带请求体,但既然是既定业务要求,你可以通过通用的exchange()方法来实现。

解决方案代码示例

直接使用exchange()自定义HTTP方法,同时设置请求体:

// 初始化RestClient(也可以用RestClient.builder()配置超时、拦截器等参数)
RestClient restClient = RestClient.create("https://your-target-server.com");

// 构造你的请求体对象
UserQueryRequest queryRequest = new UserQueryRequest();
queryRequest.setUserId(123);
queryRequest.setIncludeDetails(true);

// 发送带请求体的GET请求
UserQueryResponse response = restClient.exchange(
        requestSpec -> requestSpec
                .method(HttpMethod.GET)
                .uri("/api/users/query")
                .body(queryRequest)
                .contentType(MediaType.APPLICATION_JSON),
        UserQueryResponse.class
);

处理响应细节(如状态码、响应头)

如果需要获取响应状态码、响应头等信息,可以返回ResponseEntity:

ResponseEntity<UserQueryResponse> responseEntity = restClient.exchange(
        requestSpec -> requestSpec
                .method(HttpMethod.GET)
                .uri("/api/users/query")
                .body(queryRequest)
                .contentType(MediaType.APPLICATION_JSON),
        ResponseEntity.class,
        UserQueryResponse.class
);

// 获取状态码和响应体
HttpStatus status = responseEntity.getStatusCode();
UserQueryResponse responseBody = responseEntity.getBody();

注意事项

  • 确保目标服务器/代理支持GET请求带请求体,有些HTTP服务器会直接拒绝这类请求;
  • 保持请求体的Content-Type与服务器端预期一致(示例中用的是JSON格式)。

内容的提问来源于stack exchange,提问作者jes.alpha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:08:14