1

在根据请求设置正文时,我可以在 Groovy 的 HTTPBuilder 中使用 Jackson 而不是 JSON-lib 吗?

例子:

client.request(method){
      uri.path = path
      requestContentType = JSON

      body = customer

      response.success = { HttpResponseDecorator resp, JSONObject returnedUser ->

        customer = getMapper().readValue(returnedUser.content[0].toString(), Customer.class)
        return customer
      }
}

在这个例子中,我在处理响应时很好地使用了 Jackson,但我相信请求使用的是 JSON-lib。

4

3 回答 3

6

与其像接受的答案中建议的那样手动设置标头并使用错误的 ContentType 调用方法,而是覆盖解析器的application/json.

def http = new HTTPBuilder()
http.parser.'application/json' = http.parser.'text/plain'

这将导致以与处理纯文本相同的方式处理 JSON 响应。纯文本处理程序为您InputReader提供了HttpResponseDecorator. 要使用 Jackson 将响应绑定到您的类,您只需要使用ObjectMapper

http.request( GET, JSON ) {

    response.success = { resp, reader ->
        def mapper = new ObjectMapper()
        mapper.readValue( reader, Customer.class )
    }
}
于 2012-12-04T03:10:08.167 回答
1

是的。要使用另一个 JSON 库来解析响应中的传入 JSON,请将内容类型设置为ContentType.TEXT并手动设置 Accept 标头,如下例所示:http: //groovy.codehaus.org/modules/http-builder/doc/contentTypes。 .html _ 您将收到 JSON 作为文本,然后您可以将其传递给 Jackson。

要在 POST 请求上设置 JSON 编码输出,只需在使用 Jackson 转换请求主体后将其设置为字符串。例子:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.1' )

import groovyx.net.http.*

new HTTPBuilder('http://localhost:8080/').request(Method.POST) {
    uri.path = 'myurl'
    requestContentType = ContentType.JSON
    body = convertToJSONWithJackson(payload)

    response.success = { resp ->
        println "success!"
    }
}

另请注意,在发布时,您必须requestContentType在设置正文之前设置

于 2011-11-04T20:44:20.037 回答
0

派对已经很晚了,但现在你可以用一种更简洁的方式来做这件事,特别是在 HTTP 调用过多的地方,例如在测试中(例如Spock):

def setup() {
    http = configure {
        request.uri = "http://localhost:8080"
        // Get your mapper from somewhere
        Jackson.mapper(delegate, mapper, [APPLICATION_JSON])
        Jackson.use(delegate, [APPLICATION_JSON])
        response.parser([APPLICATION_JSON]) { config, resp ->
            NativeHandlers.Parsers.json(config, resp)
        }
    }
}
于 2020-06-11T09:20:19.703 回答