使用Groovy的HTTPBuilder发布JSON数据

Chr*_*say 13 groovy post json nullpointerexception 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 ->
        // response handling here
    }
}
Run Code Online (Sandbox Code Playgroud)

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

java.lang.NullPointerException
    at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*ska 18

我看了一下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: 'construction worker']
    requestContentType = ContentType.JSON

    response.success = { resp ->
        println "Success! ${resp.status}"
    }

    response.failure = { resp ->
        println "Request failed with status ${resp.status}"
    }
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*ert 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}"
    }
}
Run Code Online (Sandbox Code Playgroud)

干杯!