Invalid HTTP Method: PATCH

Hrishabh Purohit
Javarevisited
Published in
3 min readMar 26, 2022

Frustrating right? When Java tells you that a valid HTTP method PATCH is not valid, as a REST API developer, your eyebrow muscles start to flex. If you are reading this and have a grin on your face (I really pray that you do), this means that you have flexed your muscles on the above Java Exception, at least once.

If you are building a Java client application that consumes a RESTful API, chances are you will often run into this exception. This is because a Java client will use the HttpURLConnection class to represent a connection to the backend API and the problem lies there.

Trivial way to connect to a HTTP URL

If you are still confused on how exactly is a PATCH http method different from the PUT http method, I think we just need recall what Jason Byrne said about the difference in one of his articles. In the world of REST, a PATCH request is targeted at updating one or more attributes of an existing resource whereas a PUT request aims at doing the same but only with a small twist wherein it has the liberty to create a new resource if none found.

No Kidding !

Yes, I am not kidding. While PATCH is a completely valid HTTP request method, Java refuses to recognize it.

I experienced this when I writing my last article, where I built a RESTful service to demonstrate the migration to Google OAuth 2.0.

I happened to have a PATCH method for a use case and was testing it using one of my Java HTTP clients.

The exception was thrown on the execution of this line:

HttpURLConnection class does not recognize this http method.

OK, so I can’t send a PATCH request through JAVA?

Before you jump into any conclusion, let me assure you that indeed there is a way to send a PATCH http request through Java. But, not a straight forward one.

So what we are experiencing here is the inability of our HTTP client, built on Java, to send certain http method type in the request metadata for the server to be able to navigate the request to its corresponding handler method.

Let’s try to fool Java !

This could be fun right?

While it is true that we are not allowed to set “PATCH” as the http request method in HttpURLConnection class, what we are allowed to do is to set any request header we want.

What I mean by this is we can use a request header, provided by the HTTP protocol, that internally overrides the http method type set in the HttpURLConnection object.

Got how we fooled Java right?

We set the http method type as “POST” originally, which is recognized by HttpURLConnection class, and set the request header “X-HTTP-Method-Override” with value “PATCH”. This does the trick.

Conclusion

In this article we observed a way to consume PATCH REST API methods through a Java http client.

Keep digging deep !

--

--