June 28, 2016

How to invoke HTTP methods like PUT,PATCH and DELETE using HttpURLConnection

     I am invoking REST web services using HttpURLConnection. Few of the rest services have operations like PUT, PATCH, and DELETE. While passing these methods in setRequestMethod() of HttpURLConnection object, I am getting the below error in response.

java.net.ProtocolException: Invalid HTTP method: PATCH

     To avoid this error and to let the HttpURLConnection execute these methods, there is a workaround which is to override the http method we are invoking. And the procedure to do it is,
  • Invoke any accepted http method like GET or POST
  • Pass the new method value to the header parameter "X-HTTP-Method-Override" to Override the method 
Below is the example: 
            URL url = new URL(mcsPatchAPIURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");

To get an idea about these methods:

GET: To get the details of a resource
PUT: To update the existing resource
POST: To create a new resource
PATCH: To update the existing resource partially
DELETE: To delete the existing resource