Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== HTTP Rest Client with JSON ====== We can do a HTTP rest request to a server in Grails. Here is how. ===== Add Rest Client Dependencies in build.gradle ===== In order to use rest client, first add the following in the ''build.gradle'' <code> compile "org.grails:grails-datastore-rest-client" </code> ===== Do Rest Request in a Controller ===== You can do it in any of your controller's method. In this example, it will convert a string into JSON, and then send it to the server ''http://127.0.0.1:8080/api/'', and finally get a JSON responds from that server. <code> def callapi() { String s = '{' + ' "name": "John",\n' + ' "age": 30,\n' + ' "cars": [\n' + ' { "name" : "Ford" , "models" : ["Fiesta", "Focus", "Mustang"] },\n' + ' { "name" : "BMW" , "models" : ["320", "X3", "X5"] },\n' + ' { "name" : "Fiat" , "models" : ["500", "Panda"] }\n' + ' ]' + '}' def jsonSlurper = new JsonSlurper() def jsonObject= jsonSlurper.parseText(s) RestBuilder rest = new RestBuilder() String url = "http://127.0.0.1:8080/api" RestResponse restResponse = rest.post(url) { accept("application/json") contentType("application/json") json {jsonObject} } JSONElement jsonElement = restResponse.json render(jsonElement) } </code> or we can do it like this with a Map<String, Object> as JSON, and timeout for the connection. <code> Map<String, Object> responseData = [ "messageID" : "testing-message", "dateTime" : "2000-01-01-01:02:03", "responseToMessage": "aaaaaa", ] RestBuilder rest = new RestBuilder(connectTimeout: 1000, readTimeout:60000) String url = "http://127.0.0.1:8080/api" RestResponse restResponse = rest.post(url) { accept("application/json") contentType("application/json") json { responseData } } JSONElement jsonElement = restResponse.json render(jsonElement) </code> ===== Additional Information ===== Here is how the server code looks like <code> class ApiController { def index() { JSONObject jsonObject = request.JSON as JSONObject render(jsonObject as JSON) } } </code> and the result from the client looks like this: {{ :grails:grails_rest_client_json.png?nolink&200 |}} grails/rest_client_with_json.txt Last modified: 2019/11/14 16:17by chongtin