javahttpurlconnection

HttpURLConnection Invalid HTTP method: PATCH


When I try to use a non-standard HTTP Method like PATCH with URLConnection:

    HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com").openConnection();
    conn.setRequestMethod("PATCH");

I get an exception:

java.net.ProtocolException: Invalid HTTP method: PATCH
at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:440)

Using a higher level API like Jersey generates the same error. Is there a workaround to issue a PATCH HTTP request?


Solution

  • Yes there is workaround for this. Use

    X-HTTP-Method-Override

    . This header can be used in a POST request to “fake” other HTTP methods. Simply set the value of the X-HTTP-Method-Override header to the HTTP method you would like to actually perform. So use following code.

    conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
    conn.setRequestMethod("POST");