使用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带请求体)
- 首先引入Apache HttpClient依赖(Maven示例):
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> </dependency>
- 配置RestTemplate使用
HttpComponentsClientHttpRequestFactory作为请求工厂:
// 初始化RestTemplate时指定请求工厂 RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
- 修正后的调用代码:
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
相关产品推荐
相关产品推荐

