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

使用RestTemplate发送带JSON请求体的GET请求报错binding element must be a struct

问题根因

默认配置下的RestTemplate底层基于JDK自带的HttpURLConnection实现,该实现不支持GET请求携带请求体,会自动忽略GET请求中的body内容,你代码中封装的JSON参数并未实际发送到服务端。

服务端返回的错误:

processing failedorg.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: [code=400, message=binding element must be a struct]

就是因为服务端没有接收到预期的JSON结构体参数导致的绑定失败。你用Insomnia可以调用成功,是因为这类专业HTTP客户端原生支持GET请求携带请求体。

另外注意你的代码存在变量名笔误:你定义的请求体变量是requestBody,但创建HttpEntity时传入的是body,请先修正这个笔误。

解决方案

方案1:替换RestTemplate底层实现为Apache HttpClient(支持GET带请求体)

  1. 首先引入Apache HttpClient依赖(Maven示例):
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>
  1. 配置RestTemplate使用HttpComponentsClientHttpRequestFactory作为请求工厂:
// 初始化RestTemplate时指定请求工厂
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
  1. 修正后的调用代码:
ResponseEntity<String> responseObject = null;
String URL = "https://myurl/endpoint";
String requestBody = "{\"requestType\":\"status\"}";
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer ***");
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(requestBody,headers);
responseObject = restTemplate.exchange(URL, HttpMethod.GET, httpEntity, String.class);

方案2:调整接口为POST请求(推荐)

GET请求携带请求体不符合HTTP/1.1规范的语义约定,很多网关、代理、缓存服务都会默认丢弃GET请求的body,兼容性很差。如果可以调整后端接口定义,建议将该接口改为POST请求,直接使用默认配置的RestTemplate即可正常调用。

内容的提问来源于stack exchange,提问作者Muskan Agarwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:15:07