使用 Groovy 的 HTTPBuilder 发布 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6831736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Posting JSON data with Groovy's HTTPBuilder
提问by Christopher Laconsay
I've found this docon 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.
我发现这个文档就如何发布使用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 ->
// 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.
我错过了什么?我将不胜感激您能提供的任何帮助。
回答by Rob Hruska
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.
我查看了HttpBuilder.java:1131,我猜测它在该方法中检索的内容类型编码器为空。
Most of the POST examples hereset the requestContentTypeproperty in the builder, which is what it looks like the code is using to get that encoder. Try setting it like this:
这里的大多数POST 示例都requestContentType在构建器中设置了属性,这就是代码用来获取该编码器的样子。尝试这样设置:
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}"
}
}
回答by Robert
I had the same problem a while ago and found a blog that noted the 'requestContentType' should be set before 'body'. Since then, I've added the comment 'Set ConentType before body or risk null pointer' in each of my httpBuilder methods.
不久前我遇到了同样的问题,发现一个博客指出“requestContentType”应该在“body”之前设置。从那时起,我在每个 httpBuilder 方法中添加了注释“在正文之前设置 ConentType 或风险空指针”。
Here's the change I would suggest for your code:
这是我建议对您的代码进行的更改:
import groovyx.net.http.ContentType
http.request(POST) {
uri.path = 'http://example.com/handler.php'
// Note: Set ConentType before body or risk null pointer.
requestContentType = ContentType.JSON
body = [name: 'bob', title: 'construction worker']
response.success = { resp ->
println "Success! ${resp.status}"
}
response.failure = { resp ->
println "Request failed with status ${resp.status}"
}
}
Cheers!
干杯!
回答by Carlos André Oliveira
If you need to execute a POST with contentType JSON and pass a complex json data, try to convert your body manually:
如果您需要使用 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 -> }
}
回答by Michael D Johnson
I found an answer in this post: POST with HTTPBuilder -> NullPointerException?
我在这篇文章中找到了答案:POST with HTTPBuilder -> NullPointerException?
It's not the accepted answer, but it worked for me. You may need to set the content type before you specify the 'body' attribute. It seems silly to me, but there it is. You could also use the 'send contentType, [attrs]' syntax, but I found it more difficult to unit test. Hope this helps (late as it is)!
这不是公认的答案,但对我有用。您可能需要在指定“body”属性之前设置内容类型。这对我来说似乎很愚蠢,但确实如此。您也可以使用“send contentType, [attrs]”语法,但我发现单元测试更加困难。希望这会有所帮助(虽然很晚)!
回答by perlyking
I gave up on HTTPBuilder in my Grails application (for POST at least) and used the sendHttpsmethod offered here.
我放弃了 Grails 应用程序中的 HTTPBuilder(至少对于 POST)并使用这里sendHttps提供的方法。
(Bear in mind that if you are using straight Groovy outside of a Grails app, the techniques for de/encoding the JSON will be different to those below)
(请记住,如果您在 Grails 应用程序之外直接使用 Groovy,则 JSON 的解码/编码技术将与下面的技术不同)
Just replace the content-type with application/jsonin the following lines of sendHttps()
只需将内容类型替换为application/json以下几行sendHttps()
httpPost.setHeader("Content-Type", "text/xml")
...
reqEntity.setContentType("text/xml")
You will also be responsible for marshalling your JSON data
您还将负责编组 JSON 数据
import grails.converters.*
def uploadContact(Contact contact){
def packet = [
person : [
first_name: contact.firstName,
last_name: contact.lastName,
email: contact.email,
company_name: contact.company
]
] as JSON //encode as JSON
def response = sendHttps(SOME_URL, packet.toString())
def json = JSON.parse(response) //decode response
// do something with json
}

