POST request via RestTemplate in JSON

Johnny B picture Johnny B · Nov 2, 2010 · Viewed 358.4k times · Source

I didn't find any example how to solve my problem, so I want to ask you for help. I can't simply send POST request using RestTemplate object in JSON

Every time I get:

org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type

I use RestTemplate in this way:

...
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
...
Payment payment= new Payment("Aa4bhs");
Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment", payment, Payment.class);

What is my fault?

Answer

kanu dialani picture kanu dialani · May 25, 2011

This technique worked for me:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);

I hope this helps