【问题标题】:How can i consume restful api from grails controller? [closed]我如何从 grails 控制器中使用 restful api? [关闭]
【发布时间】:2019-07-08 11:48:36
【问题描述】:

我从一家移动公司购买了批量短信。他们为我提供了 api 文档。我可以通过 ajax 调用使用 api 发送消息。但出于安全问题,我想从服务器端而不是客户端使用 api。

我已经尝试过 grails.plugins.rest.client.RestBuilder 但没有得到适当的文档。

在我使用的插件依赖中:编译“org.grails.plugins:rest-client-builder:2.1.1”

我想使用我的 grails 控制器中的 api

【问题讨论】:

  • 您能否提供一些代码并告诉我们您到目前为止尝试了什么?举个例子就好了!

标签: java api grails


【解决方案1】:

这个问题似乎很宽泛。有很多方法可以从任何 JVM 应用程序(包括 Grails 应用程序)进行休息调用。

一种常见的方法是使用org.grails:grails-datastore-rest-client 中的RestBuilder

def rest = new RestBuilder()

// generate a GET request
def response = rest.get('https://someurl.com/someuri')
def json = response.json
def firstName = json.firstName
def lastName = json.lastName
// etc...

// generate a POST request
response = rest.post('https://someurl.com/someuri') {
    // this results in the body of the request being
    // {"firstName":"Jeff","lastName":"Brown"} and
    // the content type being set to application/json
    json {
        firstName = 'Jeff'
        lastName = 'Brown'
    }
}

【讨论】:

  • 最后,下面的代码解决了我的目的。感谢@Jeff Scott Brown 的帮助。 def rest = new RestBuilder() MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>() form.add("UserID", "****") form.add("Passwor", "******") form.add("stuID", "*******") def resp = rest.post("url") { accept JSONObject, 'application/json' contentType("application/x-www-form-urlencoded") body(form) } def json = resp.json System.out.println(json)
  • 我无法重现您所描述的问题。似乎工作正常,但也许我错过了你项目中的一些东西。我很高兴你能成功。
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
相关资源
最近更新 更多