In Spring Boot, you make a simple http request as below:
1. Define RestTemplate bean
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
2. Autowire RestTemplate wherever you need to make Http calls
@Autowire private RestTemplate restTemplate;
3. Use auto-wired RestTemplate to make the Http call
restTemplate.exchange("http://localhost:8080/users", HttpMethod.POST, httpEntity, String.class);
Above setup works fine for all Http calls except PATCH. The following exception occurs if you try to make a PATCH request as above
Exception:
I/O error on PATCH request for \"http://localhost:8080/users\": Invalid HTTP method: PATCH; nested exception is java.net.ProtocolException: Invalid HTTP method: PATCH
Cause:
Above exception happens because of the HttpURLConnection used by default in Spring Boot RestTemplate which is provided by the standard JDK HTTP library.
More on this at this bug
Fix:
This can be resolved by adding new HttpRequestFactory to the RestTemplate instance which can handle PATCH as below. Some HttpRequestFactories provided by different libraries(Spring, Apache Http) handle this PATCH as a PUT internally.
Code to add HttpRequestFactory to RestTemplate:
@Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); restTemplate.setRequestFactory(requestFactory); return restTemplate; }
You can use any of the following HttpRequestFactory's as well if the associated libraries are used in your project:
OkHttpClientHttpRequestFactory - OkHttp2 OkHttp3ClientHttpRequestFactory - OkHttp3 Netty4ClientHttpRequestFactory - Netty4
Happy coding 👨💻
Comments
Post a Comment