====== 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''
compile "org.grails:grails-datastore-rest-client"
===== 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.
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)
}
or we can do it like this with a Map as JSON, and timeout for the connection.
Map 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)
===== Additional Information =====
Here is how the server code looks like
class ApiController {
def index() {
JSONObject jsonObject = request.JSON as JSONObject
render(jsonObject as JSON)
}
}
and the result from the client looks like this:
{{ :grails:grails_rest_client_json.png?nolink&200 |}}