Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST with HTTPBuilder -> NullPointerException?

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
        }
    }
    []
}
like image 381
Stefan Kendall Avatar asked May 12 '10 23:05

Stefan Kendall


2 Answers

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
        }
    }
    []
}
like image 90
ataylor Avatar answered Nov 15 '22 07:11

ataylor


This works:

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

        send URLENC, [string1: "", string2: "heroes"]
like image 40
Stefan Kendall Avatar answered Nov 15 '22 07:11

Stefan Kendall