Search code examples
resttemplatejson-patch

patchForObject how to?


I would like to send an HTTP PATCH request via Spring RestTemplate containing an array of operations represented by following object:

@Data
@AllArgsConstructor
public class JsonOperation {
    private String op;
    private String path;
    private String value;
}

considering following code:

List<JsonOperation> operations = new ArrayList<>();
operations.add(new JsonOperation("replace", "/path1", "value1"));
operations.add(new JsonOperation("replace", "/path2", "value2"));
operations.add(new JsonOperation("replace", "/path3", "value3"));

is it possible to do the reqeust using restTemplate as follows?

restTemplate.patchForObject(url+"/toPatch/"+toPatchId, operations, ResponseEntity.class);

Solution

  • Because of a Bug the default RestTemplate of Spring does not send Http Patch requests.

    As work around the org.springframework.http.client.HttpComponentsClientHttpRequestFactory can be used to overrride the RestTemplate:

    @Bean
    public RestTemplate httpComponentsClientRestTemplate() {
        final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3000);
        requestFactory.setReadTimeout(3000));
        return new RestTemplate(requestFactory);
    }