如何在grails应用程序中使用API

时间:2013-10-14 19:45:44

标签: json rest grails

我在此网址上运行了一项服务:http://localhost:8888

我通过这样调用来获得此服务的结果:

http://localhost:8888/colors?colorname=red&shade=dark

我在JSON中得到的结果如下:

 {
      "request#": 55,
      "colorname": "red",
      "shade": "dark",
      "available": "No"
 }

问题

在Grails应用程序中,我可以通过哪些方式使用此服务?

2 个答案:

答案 0 :(得分:13)

假设rest client builder的所有配置都存在,那么最终会得到2 消费服务的代码行:

//controller/service/POGO
def resp = rest.get("http://localhost:8888/colors?colorname=red&shade=dark")
resp.json //would give the response JSON

,其中

//resources.groovy
beans = {
    rest(grails.plugins.rest.client.RestBuilder)
}

答案 1 :(得分:0)

我对使用RestBuilder plugin引入Grails 2.5.6应用程序的rest-client-builder有经验。我们不需要为RestBuilder中的resource.groovy类声明一个bean。

下面是我为my article演示的示例。

JSONElement retrieveBioModelsAllCuratedModels() {
    final String BM_SEARCH_URL = "https://wwwdev.ebi.ac.uk/biomodels/search?domain=biomodels"
    String queryURL = """\
${BM_SEARCH_URL}&query=*:* AND curationstatus:\"Manually curated\" AND NOT isprivate:true&format=json"""
    RestBuilder rest = new RestBuilder(connectTimeout: 10000, readTimeout: 100000, proxy: null)
    def response = rest.get(queryURL) {
        accept("application/json")
        contentType("application/json;charset=UTF-8")
    }
    if (response.status == 200) {
        return response.json
    }
    return null
}