2010-05-12 13 views
9

मैं एक साधारण HTTP पोस्ट अनुरोध करने की कोशिश कर रहा हूं, और मुझे नहीं पता कि निम्नलिखित क्यों विफल हो रहा है। मैंने here उदाहरणों का पालन करने का प्रयास किया, और मुझे नहीं पता कि मैं कहां गलत हो रहा हूं।पोस्ट -> 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

यह निश्चित यह मेरे लिए है। 'URLENC भेजें, [string1:" ", string2:" नायक "] 'भी काम करेगा, लेकिन HTTPBuilder का मज़ाक उड़ाते समय इकाई परीक्षण के लिए कठिन बनाता है। –

0

आप contentType JSON के साथ एक पोस्ट निष्पादित और एक जटिल 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 -> } 
}  
संबंधित मुद्दे