我试图提出一个简单的HTTP请求,我不知道为什么下面的内容会失败。我试着遵循这里的例子,但我不知道我哪里出了问题。
异常
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
}
}
[]
}发布于 2010-05-13 00:37:29
这样做是可行的:
http.request(POST) {
uri.path = '/search/'
send URLENC, [string1: "", string2: "heroes"]发布于 2010-05-18 16:25: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
}
}
[]
}发布于 2013-11-21 14:53:11
如果需要使用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 -> }
} https://stackoverflow.com/questions/2823590
复制相似问题