9

我正在尝试发出一个简单的 HTTP POST 请求,但我不知道为什么以下失败。我尝试按照此处的示例进行操作,但我看不出哪里出错了。

例外

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

3 回答 3

21

我发现有必要在分配正文之前设置内容类型。这对我有用,使用 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
        }
    }
    []
}
于 2010-05-18T16:25:19.117 回答
2

这有效:

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

        send URLENC, [string1: "", string2: "heroes"]
于 2010-05-13T00:37:29.863 回答
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 -> }
}    
于 2013-11-21T14:53:11.987 回答