6

I need to make a call to a service using Spring's RestTemplate using the HTTP PATCH verb. From what I read I need to use the execute() or exchange() method, but I have no idea on how to use it. The service call returns a HTTP 200 OK status, as well as a JSON object which I'm not particularly interested in.

Any help will be appreciated thanks.

Reezy
  • 984
  • 1
  • 9
  • 12
  • I'm not an expert of the topic, but I don't think you can do that until it's supported by RestTemplate. What you can do though is to use something like `@RequestMapping(method = RequestMethod.PATCH)`. Here's a nice tutorial how to start with: http://www.ibm.com/developerworks/web/library/wa-spring3webserv/index.html – rlegendi Jan 28 '14 at 07:51
  • `RequestMethod` is server-side, but the question is about client side support. `RestTemplate` does support PATCH (as of some point in 2012, https://jira.spring.io/browse/SPR-7985). So I'm not really sure what the question is. Did you try something (what?) and it didn't work (how did you know?)? – Dave Syer Mar 08 '14 at 11:24
  • +1. Did you find an answer to this question. Lucas's answer below does not seem complete as all the other instance variables in EmailPatch class in his example would become null - which is not the intent. Only the instance variable that needs to be changed should be sent in the request. – SGB Apr 04 '15 at 13:40

1 Answers1

6

It is possible to use the PATCH verb, but you must use the Apache HTTP client lib with the RestTemplate class with exchange(). The mapper portion may not be necessary for you. The EmailPatch class below only contains the field 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);
Lucas Holt
  • 3,826
  • 1
  • 32
  • 41
  • What happens if EmailPatch has other instance variable, say for eg; String name, string type ? Wouldn't the PATCH request update all of them to null in your example? – SGB Apr 04 '15 at 13:37
  • It will only patch what you send. If EmailPatch has other instance variables and you don't define them, it will set them to null. – Lucas Holt Apr 04 '15 at 21:59