【问题标题】:Is there a simple way to fetch a JSON dataset from a remote server in Grails?有没有一种简单的方法可以从 Grails 中的远程服务器获取 JSON 数据集?
【发布时间】:2011-01-06 13:06:16
【问题描述】:

有没有一种简单的方法可以从 Grails 中的远程服务器获取 JSON 数据集?

例如http://example.com/data.json的数据

数据:

{
    "firstName": "John",
    "lastName": "Smith"
}

示例 Groovy 代码(理论):

def data = getJson('http://example.com/data.json')
println data.firstName // this will print "John"

【问题讨论】:

  • 是否支持 JSONP?大多数环境中禁止跨域 AJAX 请求(出于安全原因;XSS 是 Web 的最大问题)。
  • @elusive 这是服务器端,所以我不确定 JSONP/XSS 是否相关

标签: grails groovy json


【解决方案1】:

我相信你应该可以做到:

import grails.converters.*

...

def data = JSON.parse( new URL( 'http://example.com/data.json' ).text )
println data.firstName

【讨论】:

  • 感谢 tim - 再简单不过了,可以吗!我会试一试,然后回复你:-)
【解决方案2】:

您可以使用Grails rest plug in,它允许您在 json 中执行 REST 请求并允许您处理所有不同的响应类型。它非常易于使用。

一个例子是这样的:

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ResponseParseException
import net.sf.json.JSONException
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.GET

...
      def restMethod() {
        try {
          def http = new HTTPBuilder("http://www.example.com")
          def path = "/exampleService/info"

          http.request(Method.POST, JSON) {req ->
            uri.path = path
            contentType = 'application/json; charset=UTF-8'
            body = "{\"arg1\":\"value4Arg1\"}"

            response.success = {resp, json ->
                // do something with the json response
            }

            response.failure = {resp ->
              // return some error code
            }
          }
        } catch (JSONException jsonException) {
          // do something with the exception
        } catch (ResponseParseException parseException) {
          // do something with the exception
        } catch (Exception e) {
         // do something with the exception
        }
      }

【讨论】:

  • 嗨@Maricel,你能添加一个使用grails-REST-plugin的例子吗?
  • 我正在尝试使用它并在 SSLSocketFactory.java:543 处获取 Internal_error。另外,您是否使用变量 contentType 和 body?
猜你喜欢
  • 2017-07-05
  • 2011-03-02
  • 2011-08-31
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 2020-04-19
相关资源
最近更新 更多