【问题标题】:Groovy httpbuilder post list paramsGroovy httpbuilder 发布列表参数
【发布时间】:2017-02-09 11:27:21
【问题描述】:

我正在尝试使用我的 grails 项目中的 Web 服务。我正在使用 httpbuilder 0.7.2。下面是我的 http 客户端。

static def webServiceRequest(String baseUrl, String path, def data,method=Method.GET,contentType=ContentType.JSON){

            def ret = null
            def http = new HTTPBuilder(baseUrl)
            http.request(method, contentType) {
                uri.path = path
                requestContentType = ContentType.URLENC
                if(method==Method.GET)
                    uri.query = data
                else
                    body = data
                headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
                response.success = { resp, json ->
                    println "response status: ${resp.statusLine}"
                    ret = json
                    println '--------------------'
                }
            }
            return ret

    }

当我试图发送这样的东西时,问题就来了:

def input = [:]
input['indexArray'] = [1,5]

api调用

def response = webServiceRequest(url,uri,input,Method.POST)

当我在我的服务器中打印发布数据的值时,它只显示列表的最后一个值。

{"indexArray":"5"}

它应该同时显示 1 和 5

【问题讨论】:

  • 你为什么用ContentType.URLENC而不是ContentType.JSON
  • 没有这个,服务器什么也收不到

标签: grails groovy httpclient httpbuilder


【解决方案1】:

如果您想使用 contenttype application/x-www-form-urlencoded 发送 json 数据,您必须在将数据添加到正文之前显式转换数据,您可以使用 (data as JSON)。

【讨论】:

    【解决方案2】:

    我正在使用 RESTClient(HTTPBuilder 上的便利包装器,https://github.com/jgritman/httpbuilder/wiki/RESTClient)。 Spock 就是这么简单。

        RESTClient restClient = new RESTClient("http://localhost:8080")
        restClient.contentType = ContentType.JSON
    

    它还会自动解析 JSON 数据,所以我的 Spock 测试是:

        when: "we check the server health"
            HttpResponseDecorator response = restClient.get([path : "/health"]) as HttpResponseDecorator
        then: "it should be up"
            response != null
            200 == response.status
            'application/json' == response.contentType
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多