2010-05-12 12 views
9

Estoy tratando de hacer una simple solicitud de HTTP POST, y no tengo idea de por qué lo siguiente está fallando. Intenté seguir los ejemplos here, y no veo dónde me estoy equivocando.POST con HTTPBuilder -> NullPointerException?

Excepción

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

Código

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

Respuesta

2

Esto funciona:

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

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

he encontrado que es necesario establecer el tipo de contenido antes de asignar el cuerpo. Esto funciona para mí, utilizando maravilloso 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

esta fijo es para mi. Usar 'send URLENC, [string1:" ", string2:" heroes "]' también funcionará, pero hace más difícil la prueba unitaria al burlarse de HTTPBuilder. –

0

Si necesita ejecutar una POST con contentType JSON y pasar un complejo de datos JSON, tratar de convertir su cuerpo de forma manual:

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 -> } 
}  
Cuestiones relacionadas