使用groovy和数据发送POST已经过URL编码

Seb*_*ien 3 groovy encoding http

我正在尝试使用Groovy HTTPBuilder发送POST,但我想发送的数据已经是URL编码的,所以我希望HTTPBuilder按原样发布它.我尝试了以下方法:

def validationString = "cmd=_notify-validate&" + postData
def http = new HTTPBuilder(grailsApplication.config.grails.paypal.server)
http.request(Method.POST) {
    uri.path = "/"
    body = validationString
    requestContentType = ContentType.TEXT

    response.success = { response ->
            println response.statusLine
    }
}
Run Code Online (Sandbox Code Playgroud)

但它给了我一个NullPointerException:

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

Dav*_*ton 6

由于您使用的是预编码的表单值,因此无法使用默认的基于地图的内容类型编码器.您必须指定内容类型,以便EncoderRegistry知道如何处理正文.

您可以使用指定正文是URL编码字符串的内容类型创建HttpBuilder:

def http = new HTTPBuilder(url, ContentType.URLENC)
Run Code Online (Sandbox Code Playgroud)

或者使请求显式传递内容类型:

http.request(Method.POST, ContentType.URLENC) {
  // etc.
Run Code Online (Sandbox Code Playgroud)

作为参考,这是我如何弄明白 - 在我阅读问题之前我不知道.

我估计总时间约为5-10分钟,比我输入的内容要短得多.希望它会说服你,但是,要找到这样的东西出来就是通过文档可能在相对较短的时间.

IMO这是开发人员培养的关键技能,让你看起来像英雄.它可以很有趣.