Search code examples
restspring-bootresttemplate

Spring boot RestClient post for object without request body results in bad request


I am trying to make a restTemplate.postForObject() without the request body and i am getting bad request.

HttpHeaders headers = new HttpHeaders();
      headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
      headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
      HttpEntity<String> entity = new HttpEntity<>(headers);

      CurrentAccount account = client.postForObject(
          "https://api.dropboxapi.com/2/users/get_current_account", entity, CurrentAccount.class);

error

Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [Error in call to API function "users/get_current_account": Bad HTTP "Content-Type" header: "application/x-www-form-urlencoded".  Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack".]

On adding

 headers.setContentType(MediaType.APPLICATION_JSON);

I get an error

Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [Error in call to API function "users/get_current_account": request body: could not decode input as JSON]

postman request works without body


Solution

  • You should also specify request body as string text "null". Yes, Dropbox Api is stating that is not required to send body when issuing POST request, but it is error somewhere between how Dropbox expecting empty JSON body representation and how spring rest template is sending the empty body JSON representation, in POST request