Search code examples
javahttpurlconnectionhttp-status-code-400http-patch

Getting error while using PATCH method in HttpURLConnection


Here from the last few hours, I am trying to update some field of resource using HttpURLConnection PUT method. But now I've changed this to PATCH.

I am able to perform GET and POST, but in Http method PATCH keep getting error.

The request not even being sent in POSTMAN.

This is the java class:

try {
    String serUrl = "https://lavazzaindia--tst1.custhelp.com/services/rest/connect/latest/tasks/255";
    String authString = user + ":" + password;
    byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
    String authStringEnc = new String(authEncBytes);

    URL url = new URL(serUrl); //Enter URL here
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
    httpURLConnection.setRequestProperty("Content-Type", "application/json");

    httpURLConnection.connect();

    String inputJson = "{   \"id\":" + 255 + "," +
        "\"assignedToAccount\": {" +
        "     \"id\":" + 233 +
        " }," +
        " \"name\":\"" + "task2_checking34" + "\"," +
        " \"serviceSettings\":{" +
        "     \"incident\":{" +
        "         \"id\":" + 380 +
        "     }" +
        " }" +
        "}";
    OutputStreamWriter osw = new OutputStreamWriter(httpURLConnection.getOutputStream());
    osw.write(inputJson);
    osw.flush();
    osw.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (httpURLConnection.getInputStream())));

    String output;
    StringBuffer bfr = new StringBuffer();
    String res = "";
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        bfr.append(output);
    }
    res = bfr.toString();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

The idea of using PATCH method in HttpUrlConnection by overriding the POST got from here.

I got the idea of sending parameters in the request body got from here.

The resources available at this url https://lavazzaindia--tst1.custhelp.com/services/rest/connect/latest/tasks/ are like

{
    "id": 253,
    "lookupName": "task_quality34",
    "createdTime": "2017-08-03T05:34:34Z",
    "updatedTime": "2017-08-03T05:34:34Z",
    "links": [{
        "rel": "canonical",
        "href": "https://lavazzaindia--tst1.custhelp.com/services/rest/connect/latest/tasks/253"
    }]
}, {
    "id": 255,
    "lookupName": "task_quality-test12",
    "createdTime": "2017-08-03T05:48:26Z",
    "updatedTime": "2017-08-03T05:48:26Z",
    "links": [{
        "rel": "canonical",
        "href": "https://lavazzaindia--tst1.custhelp.com/services/rest/connect/latest/tasks/255"
    }]
}

And I am trying to update some field of this resource , using PATCH method at this url https://lavazzaindia--tst1.custhelp.com/services/rest/connect/latest/tasks/255

But every time I am getting error

java.io.IOException: Server returned HTTP response code: 400 for URL: https://lavazzaindia--tst1.custhelp.com/services/rest/connect/latest/tasks/255
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.cloud.task.TaskUpdate.main(TaskUpdate.java:80)

Please someone help me out here to fix this.


Solution

  • Well, I'm answering own question.

    I just modified few lines of code and it worked for me. Following is the working code:

            try {
                URL url = new URL(serUrl); //Enter URL here
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
                httpURLConnection.setRequestProperty("Accept", "application/json");
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                httpURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
                httpURLConnection.connect();
    
                DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                wr.write(inputJson.getBytes());
                wr.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (httpURLConnection.getInputStream())));
    
    
                StringBuffer bfr = new StringBuffer();
                String output = "";
                String res = "";
    
                while ((output = br.readLine()) != null) {
                    bfr.append(output);
                }
                resCode = httpURLConnection.getResponseCode();
    //            System.out.println("response code = "+resCode);
                if (resCode != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + resCode +"\n"
                            +bfr.toString());
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    In the variable inputJson we shouldn't send the parameter id while it's already in the url.

    I was keep trying with the numbers of example programs, and finally resource was getting updated.