1

I'm trying to consume a web service from my grails project. I'm using httpbuilder 0.7.2. Below is my http client.

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

    }

The issue is coming when i'm trying to send something like this:

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

api call

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

when i'm printing the value of post data in my server it shows only last value of list.

{"indexArray":"5"}

it should show both 1 and 5

YoYo Honey Singh
  • 464
  • 1
  • 4
  • 21

2 Answers2

0

If you want to send json data using contenttype application/x-www-form-urlencoded you have to explicitly convert the data before adding it to the body, you can use (data as JSON).

Dennie de Lange
  • 2,776
  • 2
  • 18
  • 31
0

I am using RESTClient (nice convenience wrapper on HTTPBuilder, https://github.com/jgritman/httpbuilder/wiki/RESTClient). It is as simple as this with Spock.

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

Also it automatically parses the JSON data, so my Spock test is:

    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
allenjom
  • 137
  • 2
  • 5