1
votes

I am calling a rest api using Postman and it gives a successful response (200 OK) using following request,

method: POST

Authorization => Type: Bearer Token => Token: saflsjdflj

Body => form-data => Key: companyId, Value: 123456

But when I call this api in spring boot using rest template it gives 400 bad request. The code is shown below,

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);

HashMap<String, String> requestBody = new HashMap<>();
requestBody.put("companyId", "123456");

HttpEntity requestEntity = new HttpEntity<>(requestBody, headers)

ResponseEntity<CompanyResponse> response = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, CompanyResponse.class);
1

1 Answers

2
votes

You have to configure restTemplate: add FormHttpMessageConverter

RestTemplate restTemplate = new RestTemplateBuilder()
                .messageConverters(
                        new MappingJackson2HttpMessageConverter(objectMapper()),
                        new FormHttpMessageConverter())
                .build()

And when sending request, you have to set MediaType.APPLICATION_FORM_URLENCODED as contentType and use MultiValueMap instead of HashMap as request body:

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.put("companyId", "123456");

HttpEntity requestEntity = new HttpEntity<>(requestBody, headers)

ResponseEntity<CompanyResponse> response = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, CompanyResponse.class);