如何使用Groovy HTTPBuilder RESTClient构造HTTP帖子

时间:2014-08-22 19:04:21

标签: groovy httpbuilder

来自the docs的帖子示例不适用于http-builder 1.7.1。

def msg = "I'm using HTTPBuilder's RESTClient on ${new Date()}"

def resp = twitter.post(
        path : 'update.json',
        body : [ status:msg, source:'httpbuilder' ],
        requestContentType : URLENC )

assert resp.status == 200
assert resp.headers.Status
assert resp.data.text == msg

def postID = resp.data.id

例外是

wslite.rest.RESTClientException: No such property: body for class: wslite.http.HTTPRequest

Trolling API,你应该如何正确构建帖子并不明显。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

使用需要登录的httpbuilder调用页面时遇到了困难。因此,分享我的工作代码。

    def http = new HTTPBuilder("http://localhost:8080/")
        def query = [ username: "testUsername", password:"testPassword"]
            http.request(Method.POST,ContentType.URLENC) {
                uri.path = "user/signin"
                uri.query = query
                headers['Content-Type']= "application/x-www-form-urlencoded" 
                response.success = {resp-> println resp.statusLine }
            }

希望这有帮助。

答案 1 :(得分:1)

基于异常,看起来您使用的是groovy-wslite库,而不是HTTPBuilder。如果是这种情况,以下情况应该有效:

def resp = twitter.post(path: 'update.json') {
    urlenc status: msg, source:'httpbuilder'
}