2013-12-17 44 views
0

我使用的Grails的REST客户端生成器插件(https://github.com/grails-plugins/grails-rest-client-builder)像这样:如何使用Grails REST客户端构建器插件指定内容类型?

final def rest = new RestBuilder(connectTimeout:connectTimeout, readTimeout:readTimeout) 
final def resp = rest.get(uri) 

因此,服务器总是返回结果为XML - 我怎么(客户端)指定我想要的结果作为JSON ?

+0

的** “的contentType” **应该做的工作。但服务提供商是否支持JSON?如果没有,那么您必须将XML转换为JSON,或者使用XML。 – Armaiti

回答

2

设置内容类型是通过contentType方法完成的。 documetnation用以下示例指出了这一点。

 def resp = rest.put("http://repo.grails.org/grails/api/security/groups/test-group"){ 
     auth System.getProperty("artifactory.user"), System.getProperty("artifactory.pass") 
     contentType "application/vnd.org.jfrog.artifactory.security.Group+json" 
     json { 
      name = "test-group" 
      description = "A temporary test group" 
     } 
    } 
1

尝试这样的:

final def rest = new RestBuilder(connectTimeout:connectTimeout, readTimeout:readTimeout) 
final def resp = rest.get(uri) { 
    accept "application/json" # Add this bit 
} 
+0

你能解释一下这个解决方案相对于接受答案的优点吗? –

+0

接受的答案对我无效。我认为接受的答案只能用于“PUT”。对于“GET”,您需要使用“接受”。在我的情况下,我得到JSON,但想要XML ... – jamesj74

+0

肯定接受'应用程序/ json'意味着你得到JSON,而不是XML。另外,HTTP方法不应该影响返回的有效负载。有趣的是,它为你工作。 –

相关问题