Rohit Naik
Rohit Naik

Reputation: 539

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

Upvotes: 6

Views: 22755

Answers (3)

amichaud
amichaud

Reputation: 1753

You can use org.json.JSONObject as an empty request body:

restTemplate.postForEntity(
            "http://<yoururl>.com",
            new org.json.JSONObject(), <YourResponseType>.class).getBody();

especially if you want that the route returns something, in which case the "null" request body would not work.

Upvotes: 1

Znas Me
Znas Me

Reputation: 210

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

Upvotes: 3

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

The error message is pretty self-explanatory. You already set Accept but you didn't set Content-Type

Add following to your headers

import org.springframework.http.MediaType;

...

headers.setContentType(MediaType.APPLICATION_JSON);

Upvotes: 1

Related Questions