2010-05-12 14 views
9

Próbuję wykonać proste żądanie HTTP POST i nie mam pojęcia, dlaczego poniższe działanie się nie udaje. Próbowałem postępować zgodnie z przykładami here i nie widzę, gdzie idę źle.POST z HTTPBuilder -> NullPointerException?

Wyjątek

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

Kod

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 
     } 
    } 
    [] 
} 

Odpowiedz

2

To działa:

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

     send URLENC, [string1: "", string2: "heroes"] 
19

Znalazłem to konieczne, aby ustawić typ zawartości przed przypisaniem ciało. To działa na mnie, używając 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 
     } 
    } 
    [] 
} 
+0

Ten stały to dla mnie. Używanie 'send URLENC, [string1:" ", string2:" heroes "]' również będzie działało, ale utrudnia test jednostkowy podczas kpienia z HTTPBuilder. –

0

Jeśli trzeba wykonać post z contentType JSON i przekazać złożonych danych json, starają się przekształcić swoje ciało ręcznie:

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 -> } 
}  
Powiązane problemy