[SalesForce] Working example of update using PATCH from Java on REST API

The REST API documentation gives an example, and mentions that is uses Http Client (by which I assume they mean Apache HttpClient?). The example is here:

https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_update_fields.htm

This does not seem to be quite right. In particular, I cannot find any class called PostMethod in Apache HttpClient. Perhaps my assumptions about that being the library in use are not right.

There are problems making the PATCH request using Jersey, as discussed here:

https://stackoverflow.com/questions/22355235/patch-request-using-jersey-client

Apache HttpClient is mentioned there as a work around.

Can anyone point me to a working example of making an update using PATCH, with Apache HttpClient, or just any way that works from Java 7? Thanks for your help.

Best Answer

I can offer you these bits of code chopped out of some Java code that uses the Apache HttpClient 3.1 and works:

private HttpClient client = new HttpClient();

public void patch(...) throws Exception {
    PostMethod patch = createPost(instanceUrl + "/services/data/"
            + API_VERSION + "/sobjects/" + sobType + "/"
            + sobIdMap.get(oldSobId) + "?_HttpMethod=PATCH"
            );
    patch.setRequestEntity(new StringRequestEntity(update.toString(),
            "application/json", "UTF-8"));
    client.executeMethod(patch);
    if (patch.getStatusCode() == ...) {
        ...
    } else {
        ...
    }
}

private PostMethod createPost(String uri) {
    PostMethod post = new PostMethod(uri);
    post.setRequestHeader("Authorization", "OAuth " + sessionId);
    return post;
}

There is a class there called PostMethod (org.apache.commons.httpclient.methods.PostMethod) and this makes use of Salesforce's "_HttpMethod=PATCH" parameter as one way of working around a PATCH being awkward to generate.

Related Topic