spring-boothttp-headersresttemplatespring-resttemplatehttpentity

sending GET request via REST template with JSON request body getting failed with binding binding element must be a struct error?


I am trying to send a GET request using REST Template with a JSON request body, but the request is failing with error,

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

I have tried hitting the endpoint using the insomnia and the request is going through successfully, There I have put 2 headers

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

And the JSON body.

My code in spring boot looks like this.

    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);

The sout for httpentity and header looks like this

httpEntity

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

headers

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

Also when I am trying to send a request without the body to another endpoint using rest template, that is getting executed successfully, so I think something with the way I am sending the body has to do with the error.


Solution

  • rest template doesn't support get request with body . for more details you can refer this article.

    If you are on Java 11 I would suggest you to use java.net.HttpClient which will fulfill your need.