POST with HTTPBuilder -> NullPointerException?
Asked Answered
N

3

9

I'm trying to make a simple HTTP POST request, and I have no idea why the following is failing. I tried following the examples here, and I don't see where I'm going wrong.

Exception

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

Code

def List<String> search(String query, int maxResults)
{
    def http = new HTTPBuilder("mywebsite")

    http.request(POST) {
        uri.path = '/search/'
        body = [string1: "", query: "test"]
        requestContentType = URLENC

        headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'

        response.success = { resp, InputStreamReader reader ->
            assert resp.statusLine.statusCode == 200

            String data = reader.readLines().join()

            println data
        }
    }
    []
}
Notate answered 12/5, 2010 at 23:51 Comment(0)
N
2

This works:

    http.request(POST) {
        uri.path = '/search/'

        send URLENC, [string1: "", string2: "heroes"]
Notate answered 13/5, 2010 at 0:37 Comment(0)
M
21

I've found it's necessary to set the content type before assigning the body. This works for me, using groovy 1.7.2:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

def List<String> search(String query, int maxResults)
{
    def http = new HTTPBuilder("mywebsite")

    http.request(POST) {
        uri.path = '/search/'
        requestContentType = URLENC
        headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
        body = [string1: "", query: "test"]

        response.success = { resp, InputStreamReader reader ->
            assert resp.statusLine.statusCode == 200

            String data = reader.readLines().join()

            println data
        }
    }
    []
}
Malvasia answered 18/5, 2010 at 16:25 Comment(1)
This fixed it for me. Using send URLENC, [string1: "", string2: "heroes"] will also work, but makes it harder to unit test when mocking HTTPBuilder.Lesterlesya
N
2

This works:

    http.request(POST) {
        uri.path = '/search/'

        send URLENC, [string1: "", string2: "heroes"]
Notate answered 13/5, 2010 at 0:37 Comment(0)
S
0

If you need to execute a POST with contentType JSON and pass a complex json data, try to convert your body manually:

def attributes = [a:[b:[c:[]]], d:[]] //Complex structure
def http = new HTTPBuilder("your-url")
http.auth.basic('user', 'pass') // Optional
http.request (POST, ContentType.JSON) { req ->
  uri.path = path
  body = (attributes as JSON).toString()
  response.success = { resp, json -> }
  response.failure = { resp, json -> }
}    
Sarabia answered 21/11, 2013 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.