RESTClient 2.0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import java.net.HttpURLConnection; class RESTClient { String url String method = "GET" String body //I want the String representation of the object you want to send (either JSON or XML) String data //This is where the response data is stored Node xml //Store the processed response for xml in here Integer status //Where the status code is held, like 200, 201, 404, 400, etc... Map headers = ["Content-Type":"text/xml", "Accept":"text/xml"] Map params HttpURLConnection request def makeRemoteCall() { request = new URL(url).openConnection() //This is set to GET by default request.setRequestMethod(method) //Use the each closure to set all the requestHeader values headers.each { name, value -> request.setRequestProperty(name, value) } //Check to see what method you are performing, if post or put then you need to write out to the stream. if(method in ['POST', 'PUT']) { request.doOutput = true request.outputStream.withWriter("ASCII") { stream -> stream << body //Hopefully your body is well formatted xml or json =D } } request.connect() status = request.getResponseCode() if(status == 200 || status == 201) { if(method in ['GET', 'POST', 'PUT']) { data = request.content.text if(headers["Content-Type"] in ["text/xml", "application/xml"] && data) { xml = new XmlParser().parseText(data) } } } return this } } |
Leave a comment
You must be logged in to post a comment.

