使用 HTTPBuilder 进行 POST ->空指针异常?
我正在尝试发出一个简单的 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
}
}
[]
}
I'm trying to make a simple HTTP POST request, and I have no idea why the following is failing. I tried following the examples here, and I don't see where I'm going wrong.
Exception
java.lang.NullPointerException
at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
...
Code
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
}
}
[]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现有必要在分配正文之前设置内容类型。这对我有用,使用 groovy 1.7.2:
I've found it's necessary to set the content type before assigning the body. This works for me, using groovy 1.7.2:
这有效:
This works:
如果您需要使用 contentType JSON 执行 POST 并传递复杂的 json 数据,请尝试手动转换您的正文:
If you need to execute a POST with contentType JSON and pass a complex json data, try to convert your body manually: