【问题标题】:Can HTTPBuilder parse a response with a different content-type to the request?HTTPBuilder 可以解析具有不同内容类型的请求的响应吗?
【发布时间】:2019-12-19 04:15:21
【问题描述】:

我们正在尝试使用 Groovy 的 HTTPBuilder 的 request 方法发送内容类型为 application/x-www-form-urlencoded 的 POST 请求,并解析来自服务器的响应,其内容类型为 application/json

库忽略响应中的Content-Type 标头,并希望将其解析为application/x-www-form-urlencoded

我们的代码如下所示:

import static groovyx.net.http.ContentType.URLENC
import static groovyx.net.http.Method.POST
import groovyx.net.http.HTTPBuilder


def http = new HTTPBuilder('https://example.com')
def result = http.request(POST, URLENC) {
    uri.path = "/some/path"
    body = [
        someProperty: "someValue"
    ]
}

我可以从线路日志中看到,请求具有 Content-Type: application/x-www-form-urlencoded 标头,响应具有 Content-Type: application/json 标头 - 并且响应是格式正确的 JSON,但 HTTPBuilder 的调试日志发出以下行:

DEBUG http.HTTPBuilder  - Parsing response as: application/x-www-form-urlencoded

确实,解析响应就像它是 x-www-urlencoded。

我查看了 HTTPBuilder 的源代码,如果请求的内容类型不是*/*,它似乎想忽略响应的内容类型。

基于此,我们已设法通过配置 HTTPBuilder 实例使其按需要工作:

http.parser.'application/x-www-form-urlencoded' = http.parser.'application/json'

...但是更改 x-www-form-urlencoded 的解析器似乎就像把撬棍带到图书馆。有没有一种惯用的方法来告诉 HTTPBuilder 对请求使用一种内容类型并使用响应的 Content-Type 标头来解析结果?

【问题讨论】:

    标签: groovy content-type httpbuilder


    【解决方案1】:

    回答我自己的问题...

    http.request 的第二个参数告诉它显式地使用该内容类型作为响应,我们可以像这样得到我们想要的结果:

    def http = new HTTPBuilder('https://example.com')
    def result = http.request(POST) {
        requestContentType = URLENC
        uri.path = "/some/path"
        body = [
            someProperty: "someValue"
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2019-07-08
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多