【问题标题】:How to consume an API in a grails application如何在 grails 应用程序中使用 API
【发布时间】:2013-10-22 11:30:07
【问题描述】:

我在这个 url 上运行了一项服务:http://localhost:8888

我通过像这样调用它从这个服务中得到结果:

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

然后我会像这样以 JSON 格式返回结果:

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

问题

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

【问题讨论】:

标签: json rest grails


【解决方案1】:

假设 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)
}

【讨论】:

    【解决方案2】:

    我体验过 RestBuilder 通过 rest-client-builder plugin 引入 Grails 2.5.6 应用程序。我们不需要在resource.groovy 中为RestBuilder 类声明一个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
    }
    

    【讨论】:

    • Hi Tung:不使用 bean 初始化可能是正确的,但最好的做法是初始化最常用的 bean,以避免每次需要时都进行新的实例化,并且 RestBuilder 经常用于一个应用程序,因此最好在资源中进行实例化(Spring最佳实践)。我认为如果你想教给年轻的 Grails 程序员正确的方法,那就是使用始终资源来进行常见的 bean init。
    • 我想在资源中声明一个 bean 取决于具体情况。在这种情况下,RestBuilder 允许为您的远程连接指定一些选项,例如连接超时或代理。如果我们使用 RestBuilder 作为依赖注入,我不知道该怎么做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多