Posting JSON data with Groovy's HTTPBuilder

Chris Laconsay picture Chris Laconsay · Jul 26, 2011 · Viewed 56.3k times · Source

I've found this doc on how to post JSON data using HttpBuilder. I'm new to this, but it is very straightforward example and easy to follow. Here is the code, assuming I had imported all required dependencies.

def http = new HTTPBuilder( 'http://example.com/handler.php' )
http.request( POST, JSON ) { req ->
    body = [name:'bob', title:'construction worker']

     response.success = { resp, json ->
        // response handling here
    }
}

Now my problem is, I'm getting an exception of

java.lang.NullPointerException
    at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)

Did I miss something? I'll greatly appreciate any help you can do.

Answer

Rob Hruska picture Rob Hruska · Jul 26, 2011

I took a look at HttpBuilder.java:1131, and I'm guessing that the content type encoder that it retrieves in that method is null.

Most of the POST examples here set the requestContentType property in the builder, which is what it looks like the code is using to get that encoder. Try setting it like this:

import groovyx.net.http.ContentType

http.request(POST) {
    uri.path = 'http://example.com/handler.php'
    body = [name: 'bob', title: 'construction worker']
    requestContentType = ContentType.JSON

    response.success = { resp ->
        println "Success! ${resp.status}"
    }

    response.failure = { resp ->
        println "Request failed with status ${resp.status}"
    }
}