使用 Groovy 的 HTTPBuilder 发布 JSON 数据 [英] Posting JSON data with Groovy's HTTPBuilder

查看:27
本文介绍了使用 Groovy 的 HTTPBuilder 发布 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了关于如何发布的这个文档使用 HttpBuilder 的 JSON 数据.我是新手,但它是非常简单的示例,易于遵循.这是代码,假设我已经导入了所有必需的依赖项.

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.

推荐答案

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

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.

大多数此处的POST示例都设置了requestContentType 属性,这就是代码用来获取该编码器的样子.尝试这样设置:

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

这篇关于使用 Groovy 的 HTTPBuilder 发布 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆