function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

PATCH example with apache HttpClient

Apache's HttpClient doesn't yet have a PatchMethod class, but its easy to do PATCH requests by override the PostMethod, e.g.



	public static void patch(String url, String sid) throws IOException {
		PostMethod m = new PostMethod(url) {
			@Override public String getName() { return "PATCH"; }
		m.setRequestHeader("Authorization", "OAuth " + sid);

		Map<String, Object> accUpdate = new HashMap<String, Object>();
		accUpdate.put("Name", "Patch test");
		accUpdate.put("AnnualRevenue", 10);
		ObjectMapper mapper = new ObjectMapper();
		m.setRequestEntity(new StringRequestEntity(mapper.writeValueAsString(accUpdate), "application/json", "UTF-8"));
		HttpClient c = new HttpClient();
		int sc = c.executeMethod(m);
		System.out.println("PATCH call returned a status code of " + sc);
		if (sc > 299) {
			// deserialize the returned error message
			List<ApiError> errors = mapper.readValue(m.getResponseBodyAsStream(), new TypeReference<List<ApiError>>() {} );
			for (ApiError e : errors)
				System.out.println(e.errorCode + " " + e.message);
	private static class ApiError {
		public String errorCode;
		public String message;
		public String [] fields;



The sample also uses the jackson json library, which I'd highly recommend for the java folks.


If you're stuck with an http library that doesn't allow for overriding, or setting an arbitary http method name, then you can send a POST request and provide an override to the http method via the query string param _HttpMethod, in the above example, you could replace the PostMethod line with this instead 



PostMethod m = new PostMethod(url + "?_HttpMethod=PATCH");