Question

Groovy HttpBuilder does not support HTTP PATCH method. How can I issue a request using one?

Was it helpful?

Solution

Since the method is passed as Enum, you can't add new methods in a normal way. Luckily, it's Groovy, so everything is possible. We'll replace org.apache.http.client method in the closure's delegate:

import groovyx.net.http.*
import org.apache.http.client.methods.HttpPatch

@Grab(group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.6')
@Grab(group = 'org.apache.httpcomponents', module = 'httpcomponents-client', version = '4.2')
def runPatch() {
    //serverinfo.groovy just returns the request method
    //Method.DELETE is switched, and won't be used (can't use null, NPE)
    new HTTPBuilder('http://localhost:9090/serverinfo.groovy').request(Method.DELETE) {
        delegate.request = new HttpPatch()
        response.success = { resp, body ->
            assert resp.status == 200
            assert body == 'PATCH'
        }
    }
}

runPatch()

OTHER TIPS

Other option - use 0.7-SNAPSHOT.

Solution for those, who prefer JAX RS Client API:

def client = ClientBuilder.newClient()
def response = client.target("$baseUrl$restUsersUrl/$userId")
        .request("application/json")
        .header("Authorization", "Basic ${authString}")
        .build("PATCH", Entity.entity(json2Update, MediaType.APPLICATION_JSON))
        .invoke()
if(Response.Status.NO_CONTENT.statusCode == response.status)
{
    println "test"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top