使用Groovy的HTTPBuilder发布JSON数据

时间:2011-07-26 14:35:47

标签: json post groovy nullpointerexception httpbuilder

我发现this doc关于如何使用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
    }
}

现在我的问题是,我得到了

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

我错过了什么吗?我非常感谢你能做的任何帮助。

5 个答案:

答案 0 :(得分:18)

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

大多数POST examples here在构建器中设置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}"
    }
}

答案 1 :(得分:8)

前一段时间我遇到了同样的问题,发现一个博客注意到'requestContentType'应该在'body'之前设置。从那时起,我在每个httpBuilder方法中添加了注释'在body或之前设置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}"
    }
}

干杯!

答案 2 :(得分:2)

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

我放弃了Grails应用程序中的HTTPBuilder(至少用于POST),并使用sendHttps提供的here方法。

(请记住,如果你在Grails应用程序之外使用直接Groovy,那么de /编码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
}