1

Having a few issues with the response handling of my httpbuilder post and json

within my service I have:

def jsonDataToPost = '{"accountNumber" : ' + accNo + ',"accountName" : ' + accName + '}'

            def http = new HTTPBuilder('https://myurl.com/dataInput')
            def jsonResponse
            http.auth.basic ('username','password')
            http.request(POST, ContentType.JSON) {
                headers.'Content-Type' = 'application/json'
                body = jsonDataToPost
                response.success = { json ->
                    println("Success")
                    jsonResponse = json
                }
                response.failure = { json ->
                    println("Fail")
                    jsonResponse = json
                }
            }

firstly for some reason the code actually skips out rather than completing and so I'm not getting the jsonReponse I'm after but I can't figure out why? If I reponse my response.success/fail and I post correct data my json post works but again I still get no json back

NewbieGrails
  • 93
  • 2
  • 11

2 Answers2

0

Try this,

       def requestData = [foo:bar]
       http.request(POST, ContentType.JSON) {
            headers.'Content-Type' = 'application/json'
            body = (requestData as JSON).toString()
            response.success = { resp, reader ->
                println("Success")
                jsonReponse = reader.text
            }
            response.failure = { resp, reader ->
                println("Failed, status: " + resp.status)
                jsonReponse = reader.text
            }
        }
raffian
  • 31,267
  • 26
  • 103
  • 174
0

If you're using Grails 3.x you can use http-builder-ng https://http-builder-ng.github.io/http-builder-ng

Ibrahim.H
  • 1,062
  • 1
  • 13
  • 22