13

我找到了这篇关于如何使用 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)

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

4

5 回答 5

18

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

此处的大多数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}"
    }
}
于 2011-07-26T15:02:47.843 回答
8

前段时间我遇到了同样的问题,发现一个博客指出“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}"
    }
}

干杯!

于 2013-04-26T19:34:07.080 回答
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 -> }
}    
于 2013-11-21T14:59:48.997 回答
1

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

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

于 2012-10-02T17:03:18.433 回答
-1

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

(请记住,如果您在 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
}
于 2012-01-31T18:46:00.120 回答