我试图从我的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 call
def response = webServiceRequest(url,uri,input,Method.POST)
当我在我的服务器上打印发布数据的值时,它只显示列表的最后一个值。
{" indexArray":" 5"}
它应该显示 1和5
答案 0 :(得分:0)
如果你想使用contenttype application / x-www-form-urlencoded发送json数据,你必须在将数据添加到正文之前显式转换数据,你可以使用(数据作为JSON)。
答案 1 :(得分:0)
我正在使用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