[JAVA] The patchForObject added to RestTemplate cannot be used effectively if it is a default implementation (the one that uses HttpURLConnection).

From Spring Framework 4.3.5, patchForObject method (method for HTTP communication using PATCH method) has been added to RestTemplate, but if RestTemplate is used in the default state, an error will occur during communication processing. It ends up: sweat_smile: This is because the class used in the default state is the JDK standard API java.net.HttpURLConnection. As some of you may know, HttpURLConnection doesn't support the PATCH method ...

What if I use PATCH?

Use an OSS library that supports the PATCH method! !!

Spring Framework supports the following OSS libraries.

All of the above libraries support PATCH methods.

How to use the OSS library?

The following steps are required.

  1. Add as a dependent library to pom.xml etc.
  2. Inject the implementation class of ClientHttpRequestFactory corresponding to the OSS library into RestTemplate

Injection example of ClientHttpRequestFactory


@Bean
RestTemplate restTemplate() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    return new RestTemplate(factory);
}

Note:

If you want to use RestTemplate on Spring Boot 1.4+, please see "Use RestTemplate (HTTP client) on Spring Boot 1.4+"! !! By generating RestTemplate using RestTemplateBuilder added in Spring 1.4, 2 of the above step will be solved automatically.

Implementation class of ClientHttpRequestFactory provided by Spring Framework

Spring Framework provides the following implementation classes.

name of the class Description
HttpComponentsClientHttpRequestFactory Apache HttpComponents Implementation class for HTTP communication using HttpClient
OkHttp3ClientHttpRequestFactory Implementation class for HTTP communication using OkHttp 3
OkHttpClientHttpRequestFactory Implementation class for HTTP communication using OkHttp 2
Netty4ClientHttpRequestFactory Implementation class for HTTP communication using Netty 4
SimpleClientHttpRequestFactory JDKHttpURLConnectionImplementation class for HTTP communication using (default implementation)

Summary

If you need to access the REST API (Web API) using the PATCH method ... Use the OSS library for HTTP communication! !!

Recommended Posts

The patchForObject added to RestTemplate cannot be used effectively if it is a default implementation (the one that uses HttpURLConnection).
If it is Ruby, it is efficient to make it a method and stock the processing.
The end of catastrophic programming # 03 "Comparison of integers, if" a> b ", assume that it is" a --b> 0 ""
Program to determine if it is a leap year
What to do if the adb command cannot be executed
[Swift5] How to create a .gitignore file and the code that should be written by default
What to do about the "cannot be read or is not a valid ZIP file" error