Reputation: 127
I've been reading the following and trying to send a POST request with Spring Boot, using RestTemplate.
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/x-www-form-urlencoded");
final String body = "clipmessage={ bridgeId: \"" + user.getBridgeId() + "\", clipCommand: { url: \"" + setLightState("3") + "\", method: \"PUT\", body: { \"on\": " + state.isOn() + " } } }";
final String url = API_ADDRESS + user.getAccessToken();
HttpEntity<String> entity = new HttpEntity<>(body, headers);
restTemplate.postForEntity(url, entity, String.class);
If I log the URL and the body and send the exact same in Postman, it succeeds. However, not when I send it from my Spring Boot application.
I'm guessing that special body has to be sent in some special way which that I am not aware off?
Anyone has any tips on what to try here next?
UPDATE 1: I tried the MultiValueMap as suggested, but did not get that to work either.
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
final String body = "{ bridgeId: \"" + user.getBridgeId() + "\", clipCommand: { url: \"" + setLightState("3") + "\", method: \"PUT\", body: { \"on\": " + state.isOn() + " } } }";
map.add("clipmessage", body);
HttpEntity<String> entity = new HttpEntity<>(body, headers);
Upvotes: 0
Views: 8058
Reputation: 418
I have the same scenario. solved after using the following code :
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
FormHttpMessageConverter formMessageConverter = new FormHttpMessageConverter();
messageConverters.add(formMessageConverter);
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
Parameters and headerpart
...
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("signature", "signature");
//other parameters
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(parameters, headers);
ResponseEntity<ResponseMessage> responseEntity = restTemplate.postForEntity(url, requestEntity, ResponseMessage.class);
ResponseMessage respMsg =responseEntity.getBody();
logMsg.append(",HTTP STATUS=").append(responseEntity.getStatusCode()).append(", RES:").append(marshal(respMsg));
Upvotes: 1