How to make a Spring RestTemplate PATCH request

I need to make a service call using Spring RestTemplate using the HTTP PATCH protocol. From what I read, I need to use the execute () or exchange () method, but I have no idea how to use it. A service call returns an HTTP status of 200 OK, as well as a JSON object that I am not particularly interested in.

Any help would be greatly appreciated.

+4
source share
1 answer

You can use the verb PATCH, but you must use the Apache HTTP client lib with the RestTemplate class with exchange (). A piece of the map may not be necessary for you. The EmailPatch class below contains only the field that we want to update in the request.

  ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
    converter.setObjectMapper(mapper);

    HttpClient httpClient = HttpClients.createDefault();
    RestTemplate restTemplate = new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter));
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); 
    EmailPatch patch = new EmailPatch();
    patch.setStatus(1);
    ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PATCH, new HttpEntity<EmailPatch>(patch),
                    String.class);
+3

Source: https://habr.com/ru/post/1523997/


All Articles