Justin
Justin

Reputation: 987

Invalid HTTP method: PATCH in Java 8

I am trying to post payload to ClientApp RESTAPI via PATCH as HTTP_METHOD in Java.

There are lot of similar ERROR found in google and got suggestion to use X-HTTP-Method-Override header.

I followed this blog code base to achieve the same.

Java Version: 1.8.0_171

Code:

package com.in.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class ConnectToCorbion {
    
    
    
    public static void main(String[] args) throws IOException {
        
         String PATCH_PARAMS = "[ { \"op\": \"replace\", \"path\": \"/optionalFields1/text1\", \"value\": \"SR234568\", \"from\" : \"string\" }]";
        String my_url = "https://uat.clientapp.com/api/ChangeActivities";
        byte[] patchData       = PATCH_PARAMS.getBytes( StandardCharsets.UTF_8 );
        URL obj = null;
        
            System.out.println("BEFORE");
            obj = new URL(my_url);
            System.out.println("AFTER");
    
        
        String username = "username";
        String password = "password";

        HttpURLConnection patchConnection = null;
    
            System.out.println("BEFORE openConnection");
            try {
                patchConnection = (HttpURLConnection) obj.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("AFTER openConnection");
            patchConnection.setRequestMethod("PATCH");
        //patchConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        
        
        
        patchConnection.setRequestProperty("Accept", "application/json");
        patchConnection.setRequestProperty("Content-Type", "application/json-patch+json");
        patchConnection.setRequestProperty("messageType", "application/json-patch+json");

        // connection code if you are using java 8 or above
        patchConnection.setRequestProperty("Authorization",
            "Basic " + Base64.getEncoder().encodeToString(
              (username + ":" + password).getBytes()
            )
        );
        // connection code if you are using java 8 or above ends here

        

        patchConnection.setDoOutput(true);
        OutputStream os = null;
        
            System.out.println("BEFORE getOutputStream");
            os = patchConnection.getOutputStream();
            System.out.println("AFTER getOutputStream");
        
    
            os.write(PATCH_PARAMS.getBytes());
        
    
            os.flush();
        
            os.close();
        

        int responseCode = 0;
        
            responseCode = patchConnection.getResponseCode();
        
        System.out.println("Response Code :  " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
            BufferedReader in = null;
        
                in = new BufferedReader(new InputStreamReader(
                        patchConnection.getInputStream()));
            
            String inputLine;
            StringBuffer response = new StringBuffer();

           
                while ((inputLine = in .readLine()) != null) {
                    response.append(inputLine);
                }
            
                in .close();
            
            System.out.println(response.toString());
        } else {
            System.out.println("PATCH NOT WORKING");
        }
        
    }

}

ERROR LOG:

BEFORE
AFTER
BEFORE openConnection
AFTER openConnection
Exception in thread "main" java.net.ProtocolException: Invalid HTTP method: PATCH
    at java.net.HttpURLConnection.setRequestMethod(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestMethod(Unknown Source)
    at com.in.Test.ConnectToCorbion.main(ConnectToCorbion.java:44)

Note: Not able to upgrade Java version as it depends on Organization infra setup.

How can i able to achieve this PATCH Request ? Kindly suggest me what went wrong or some other way to achieve the same

Upvotes: 1

Views: 4287

Answers (1)

evren
evren

Reputation: 140

"PATCH" is not supported with Java 8 for setRequestedMethod within HttpURLConnection. You can use "POST" instead and set "X-HTTP-Method-Override" header attribute to "PATCH" as a work-around solution.

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

Upvotes: 1

Related Questions