1

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.

Shambhu
  • 181
  • 6
  • 16
  • is this service documented anywhere? only the service can tell how to build a proper request – nandsito Aug 03 '17 at 11:38
  • I've successful build `GET` and `POST` request using `HttpUrlConnection`. But in `PUT` method plsguide me in codes whether I am doing any wrong. – Shambhu Aug 03 '17 at 11:41
  • refer to my comment above. I have no idea what that HTTP endpoint expects – nandsito Aug 03 '17 at 11:45
  • @SNSingh, The 400 Bad request can be mostly by url encoding , but you are saying you have done GET and POST method call successfully, Then i doubt the parameters in json is missing or are added extra which you are sending in PUT. – Raju Sharma Aug 03 '17 at 11:46
  • @nandsito ok, I've added the resources available at the endpoint and by entering in any of these after just adding id with this. I am able to create new resource using `POST` but now not able update the existing one. – Shambhu Aug 03 '17 at 11:49
  • @RajuSharma I've checked this, I can send parameters whatever I want to update in that resource, the only thing I've to use `PATCH` method, but I'm getting the same error. – Shambhu Aug 03 '17 at 12:56
  • For the record, `HttpURLConnection` doesn't support the PATCH method, and many other verbs. Only GET, PUT, POST, and DELETE as far as I know, and maybe HEAD. If you want to use other verbs you will need to use a different HTTP client, such as the Apache one, or this X-HTTP-Method-Override header. – user207421 Aug 28 '17 at 06:14

1 Answers1

0

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.

Shambhu
  • 181
  • 6
  • 16