使用 Groovy 的 HTTPBuilder 发布 JSON 数据

发布于 2024-11-26 02:57:38 字数 644 浏览 3 评论 0原文

我找到了此文档,了解如何使用HttpBuilder。我对此很陌生,但它是非常简单的示例并且易于理解。这是代码,假设我已经导入了所有必需的依赖项。

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
    }
}

现在我的问题是,我遇到了一个例外:

java.lang.NullPointerException
    at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)

我错过了什么吗?我将非常感谢您能提供的任何帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暮倦 2024-12-03 02:57:38

我查看了 HttpBuilder.java:1131,我猜测它在该方法中检索的内容类型编码器为空。

大多数此处的 POST 示例都设置了 requestContentType<构建器中的 /code> 属性,这就是代码用来获取该编码器的属性。尝试这样设置:

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}"
    }
}

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}"
    }
}
晚雾 2024-12-03 02:57:38

我不久前遇到了同样的问题,发现一个博客指出“requestContentType”应该设置在“body”之前。从那时起,我在每个 httpBuilder 方法中添加了注释“在正文之前设置 ConentType 或风险空指针”。

这是我建议对您的代码进行的更改:

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}"
    }
}

干杯!

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.

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!

鲜肉鲜肉永远不皱 2024-12-03 02:57:38

如果您需要使用 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 -> }
}    

If you need to execute a POST with contentType JSON and pass a complex json data, try to convert your body manually:

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 -> }
}    
小兔几 2024-12-03 02:57:38

我在这篇文章中找到了答案: POST with HTTPBuilder -> NullPointerException?

这不是公认的答案,但它对我有用。您可能需要在指定“body”属性之前设置内容类型。对我来说这似乎很愚蠢,但事实就是如此。您还可以使用“send contentType, [attrs]”语法,但我发现单元测试更困难。希望这会有所帮助(虽然已经晚了)!

I found an answer in this post: 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)!

陌路黄昏 2024-12-03 02:57:38

我放弃了 Grails 应用程序中的 HTTPBuilder(至少对于 POST)并使用了此处提供的 sendHttps 方法< /a>.

(请记住,如果您在 Grails 应用程序之外直接使用 Groovy,则对 JSON 进行解码/编码的技术将与下面的技术不同)

只需将内容类型替换为 application/json以下几行 sendHttps()

httpPost.setHeader("Content-Type", "text/xml")
...
reqEntity.setContentType("text/xml")

您还将负责编组 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
}

I gave up on HTTPBuilder in my Grails application (for POST at least) and used the sendHttps method offered here.

(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)

Just replace the content-type with application/json in the following lines of sendHttps()

httpPost.setHeader("Content-Type", "text/xml")
...
reqEntity.setContentType("text/xml")

You will also be responsible for marshalling your JSON data

 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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文