2010-05-12 1 views
9

간단한 HTTP POST 요청을하려고하는데 다음 이유가 무엇인지 알 수 없습니다. 나는 예제 here을 따라했지만, 나는 어디가 잘못 될지 보지 못했다.POST with HTTPBuilder -> NullPointerException?

예외

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

코드이 작동

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

답변

2

는 :

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

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

나는 몸을 할당하기 전에 내용 유형을 설정하는 것이 필요 발견했습니다. 이것은 사용, 나를 위해 작동 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

이 고정에게 그것은 나를 위해. 'send URLENC, [string1 : "", string2 : "heroes"]'도 사용 가능하지만, HTTPBuilder를 조롱 할 때 유닛 테스트가 더 어려워집니다. –

0

당신의 contentType JSON과 POST를 실행하고 복잡한 JSON 데이터를 전달해야 할 경우, 수동으로 몸을 변환하려고 :

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