我正在尝试发出一个简单的HTTP POST请求,我不知道为什么以下是失败的。我尝试按照例子here进行操作,但我没有看到我出错的地方。
异常
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
}
}
[]
}
答案 0 :(得分:19)
我发现在分配正文之前必须设置内容类型。这适用于我,使用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
}
}
[]
}
答案 1 :(得分:2)
这有效:
http.request(POST) {
uri.path = '/search/'
send URLENC, [string1: "", string2: "heroes"]
答案 2 :(得分: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 -> }
}