使用Groovy的HTTPBuilder发布JSON数据 [英] Posting JSON data with Groovy's HTTPBuilder
问题描述
我发现了此文档如何发布使用HttpBuilder的JSON数据。我对此很陌生,但这是一个非常直接的例子,很容易遵循。这是代码,假设我已经导入了所有必需的依赖项。
def http = new HTTPBuilder('http:// example。 com / handler.php')
http.request(POST,JSON){req - >
body = [name:'bob',title:'construction worker']
response.success = {resp,json - >
//在这里处理的响应
}
}
现在我的问题是,我在groovyx.net.http中遇到了
java.lang.NullPointerException
的异常。 HTTPBuilder $ RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
我错过了什么吗?我非常感谢你能做的任何帮助。
www.jarvana.com/jarvana/view/org/codehaus/groovy/modules/http-builder/http-builder/0.5.0/http-builder-0.5.0-all.zip!/http-builder-0.5.0 /src/main/java/groovyx/net/http/HTTPBuilder.javarel =noreferrer> HttpBuilder.java:1131 ,我猜测它在该方法中检索的内容类型编码器是null。大部分这里的POST例子在构建器中设置 requestContentType
属性,这看起来像代码用来获取该编码器。尝试像这样设置它:
import groovyx.net.http.ContentType
http.request( POST){
uri.path ='http://example.com/handler.php'
body = [name:'bob',title:'建筑工人']
requestContentType = ContentType.JSON
response.success = {resp - >
printlnSuccess!$ {resp.status}
}
response.failure = {resp - >
println请求失败,状态为$ {resp.status}
}
}
I've found this doc on how to post JSON data using HttpBuilder. I'm new to this, but it is very straightforward example and easy to follow. Here is the code, assuming I had imported all required dependencies.
def http = new HTTPBuilder( 'http://example.com/handler.php' )
http.request( POST, JSON ) { req ->
body = [name:'bob', title:'construction worker']
response.success = { resp, json ->
// response handling here
}
}
Now my problem is, I'm getting an exception of
java.lang.NullPointerException
at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
Did I miss something? I'll greatly appreciate any help you can do.
I took a look at HttpBuilder.java:1131, and I'm guessing that the content type encoder that it retrieves in that method is null.
Most of the POST examples here set the requestContentType
property in the builder, which is what it looks like the code is using to get that encoder. Try setting it like this:
import groovyx.net.http.ContentType
http.request(POST) {
uri.path = 'http://example.com/handler.php'
body = [name: 'bob', title: 'construction worker']
requestContentType = ContentType.JSON
response.success = { resp ->
println "Success! ${resp.status}"
}
response.failure = { resp ->
println "Request failed with status ${resp.status}"
}
}
这篇关于使用Groovy的HTTPBuilder发布JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!