groovy - Another issue when trying to POST JSON to REST URL via HttpBuilder -
i read this , several other postings on , elsewhere how send post call via httpbuilder json data content. problem none of solutions working!
my problem different. i have existing json data in file. when attempt send rest interface curl:
curl -x post -u "username:password" -d @/path/to/myfile.json http://localhost:8080/path/here --header "content-type:application/json"   all works well. here @ (some code in there, read on):
def myfile = new file('/path/to/myfile.json') if (!myfile.exists()) println "error!  not have json file!"  def convertedtext = myfile.text.replaceall('\\{', '[') convertedtext = convertedtext.replaceall('\\}', ']')   def jsonbldr = new jsonbuilder() jsonbldr myfile.text  println jsonbldr.tostring()  def myclient = new groovyx.net.http.httpbuilder('http://username:password@localhost:8080/my/path') myclient.setheaders(accept: 'application/json')  results = myclient.request(post, json) { req ->     body = [ jsonbldr.tostring() ]     requestcontenttype = json     response.success = { resp, reader ->         println "success! ${resp.statusline}"     }      response.failure = { resp ->         println "failure! ${resp.properties}"     } }   this results in 'failure' closure data:
statusline:http/1.1 400 exception evaluating property 'id' java.util.arraylist, reason: groovy.lang.missingpropertyexception: no such property: id class: java.lang.string   fwiw, there no "id" in json anywhere. if change "body" line "[ jsonbldr.tostring() ]" "[ convertedtext ]" - why code there, same error. if take out brackets on body, error stating body not data array (as map).
can (far groovier i) tell me %%$#@ doing wrong???
you need jsonslurper instead of jsonbuilder. after implementation like:
def myfile = new file('/path/to/myfile.json') if (!myfile.exists()) println "error!  not have json file!"  def bodymap = new jsonslurper().parsetext(myfile.text)  def myclient = new groovyx.net.http.httpbuilder('http://username:password@localhost:8080/my/path') modelclient.setheaders(accept: 'application/json')  results = myclient.request(post, json) { req ->     requestcontenttype = json     body = bodymap     response.success = { resp, reader ->         println "success! ${resp.statusline}"     }      response.failure = { resp ->         println "failure! ${resp.properties}"     } }   however, not clear difference between myfile , modelfile in code.
Comments
Post a Comment