【发布时间】: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