Use HTTP PATCH with Spring Boot OpenFeign

,

The problem

In case, like me, you want to use a Feign Client in your Spring Boot application, you might find yourself needing to use it to perform a PATCH request and you’d expect it to work. However, you’ll run into an exception with a stack trace like the one below.🤦‍♂️

feign.RetryableException: Invalid HTTP method: PATCH executing PATCH https://your-url.com/
	at feign.FeignException.errorExecuting(FeignException.java:300) ~[feign-core-13.5.jar:na]
	at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:105) ~[feign-core-13.5.jar:na]
	at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:53) ~[feign-core-13.5.jar:na]
	at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:104) ~[feign-core-13.5.jar:na]
	at jdk.proxy2/jdk.proxy2.$Proxy57.updateIp(Unknown Source) ~[na:na]
	...
Caused by: java.net.ProtocolException: Invalid HTTP method: PATCH
	at java.base/java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:491) ~[na:na]
	at java.base/sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:607) ~[na:na]
	at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java:343) ~[na:na]
	at feign.Client$Default.convertAndSend(Client.java:176) ~[feign-core-13.5.jar:na]
	at feign.Client$Default.execute(Client.java:109) ~[feign-core-13.5.jar:na]
	at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:92) ~[feign-core-13.5.jar:na]
	... 13 common frames omitted

If you look online for the error, you will find the cause to be the fact the the HTTP client used by default by spring-cloud-openfeign uses Java’s HttpURLConnection, which apparently does not recognize PATCH as a valid HTTP verb. 🤷‍♂️

Most results also suggest to switch the client to feign-okhttp, but I only found one proper suggestion how to enable it. Most others were wrong because they were meant for older versions of Spring Boot.


The solution

So hopefully I can save you some time by giving you the solution. You need to import the feign-okhttp dependency:

<dependency>
	<groupId>io.github.openfeign</groupId>
	<artifactId>feign-okhttp</artifactId>
	<version>13.5</version>
</dependency>

In order to enable it, you should set the following property in your application.properties file:

spring.cloud.openfeign.okhttp.enabled=true

The component versions that I’ve used, for which I know the solution surely works, are:

  • Spring Boot: 3.3.6
  • spring-cloud-starter-openfeign: 4.1.4
  • feign-okhttp: 13.5

An important resource to figure this out was the official OpenFeign documentation, which can be found here: https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/ .

Hope this helps, have fun clickity-clacking.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *