I have a question how to make a PUT operation with Spring REST DATA and RestTemplate to update a relation between two beans.
I am successfully updating with curl, but I could not manage to do it with RestTemplate.
curl -i -X PUT -d 'http://localhost:8383/services/67' -H "Content-Type:text/uri-list" localhost:8383/routes/135/service
This works, it updates my Route object with a reference to Service object 67 but I try to do this with following RestTemplate, it is not.
ResponseEntity<Route> responseEntity = restTemplate.exchange("http://localhost:8383/routes/", HttpMethod.POST, requestEntity, Route.class);
if(responseEntity.getStatusCode() == HttpStatus.CREATED) {
HttpHeaders reqHeaders = new HttpHeaders();
reqHeaders.add(HttpHeaders.CONTENT_TYPE, new MediaType("text", "uri-list").toString());
HttpEntity<Service> requestEntityService = new HttpEntity<>(service, reqHeaders);
restTemplate.put("http://localhost:8383/routes/" + responseEntity.getBody().getId() + "/service", requestEntityService);
}
If I try to this, it complains about it can't find any MessageConverter's for 'uri-list' but if I remove the 'uri-list' then Spring Rest Data responds with '404' because it seems it does this operation only with 'uri-list'..
While I also use the Spring HATEOAS project, I defined a special MessageConvter,....
@Bean
private RestTemplate prepareRestTemplate(RestTemplateBuilder restTemplateBuilder) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setDefaultCharset(Charset.forName("UTF-8"));
converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); converter.setObjectMapper(objectMapper);
return restTemplateBuilder.messageConverters(converter).build();
}
This works perfectly for POST operation and creating beans in Spring Rest Data, do I also have to defined MediaType 'uri-list' here.
I see lot of examples in the internet how to do this with curl but none how to do it with RestTemplate, of course I can use HttpClient to do this but naturally this will be weird.
Any tips?
Thx for answers