【问题标题】:sending GET request via REST template with JSON request body getting failed with binding binding element must be a struct error?通过带有 JSON 请求正文的 REST 模板发送 GET 请求失败,绑定绑定元素必须是结构错误?
【发布时间】:2021-12-16 16:50:42
【问题描述】:

我正在尝试使用带有 JSON 请求正文的 REST 模板发送 GET 请求,但请求失败并出现错误,

处理 failedorg.springframework.web.client.HttpServerErrorException$InternalServerError: 500 内部服务器错误:[code=400,message=binding element must be 一个结构]

我已经尝试使用 insomnia 访问端点并且请求成功通过,我已经放置了 2 个标头

1. Content-Type - application/json
2. Authorization - Bearer ******

还有 JSON 正文。

我在 Spring Boot 中的代码是这样的。

    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 httpEntity = new HttpEntity<>(body,headers);
    System.out.println(httpEntity+" httpEntity");
    System.out.println(headers+" headers");
    responseObject = restTemplate.exchange(URL, HttpMethod.GET, httpEntity, String.class);

httpentity 和 header 的 sout 如下所示

httpEntity

<{"requestType":"status"},[Authorization:"Bearer *******************", Content-Type:"application/json"]>

标题

[Authorization:"Bearer *************************", Content-Type:"application/json"]

此外,当我尝试使用 rest 模板将没有正文的请求发送到另一个端点时,该请求已成功执行,因此我认为我发送正文的方式与错误有关。

【问题讨论】:

    标签: spring-boot http-headers resttemplate spring-resttemplate httpentity


    【解决方案1】:

    rest 模板不支持使用 body 获取请求。更多详情可以参考this article

    如果您使用的是 Java 11,我建议您使用 java.net.HttpClient,这将满足您的需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-03
      • 2017-02-18
      • 2021-02-17
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      相关资源
      最近更新 更多