jsonhttpclientapache-httpcomponentshttp-patch

How do I use the Apache HttpClient library to submit a PATCH request with JSON data?


I’m using Apache HTTP client v 4.3.4. How do I submit JSON data to a URL via the PATCH method? I have tried this

    // Create the httpclient
    HttpClient httpclient = HttpClientBuilder.create().build();

    // Prepare a request object
    HttpUriRequest req = null;
    if (method.equals(RequestMethod.PATCH))
    {
        req = new HttpPatch(url);
        req.setHeader("Content-type", "application/json");
        if (jsonData != null)
        {
            final StringEntity stringData = new StringEntity(jsonData.toString());
            req.setEntity(stringData);
        }   // if

but on the “req.setEntity” line, I get the compilation error, “The method is undefined”. Note that my request needs to send the JSON data as is, as opposed to putting it into a name-value param pair.


Solution

  • You have cast the HttpPatch object is implicity cast to HttpUriRequest in your code.

    The HttpUriRequest interface does not support the setEntity method so you need to cast:

    ((HttpPatch)req).setEntity(stringData);