2016-08-27 96 views
2

我必须在Web应用程序中编写一个小脚本。这个网络应用程序有它的局限性,但类似于这个在线控制台:https://groovyconsole.appspot.com/所以如果它在这里工作,它也应该为我的问题。如何在Groovy中获得REST响应?

我需要解析一个JSON响应。为了简单起见,我开发了C#自己的Web API,当我在浏览器上输入链接(http://localhost:3000/Test)就给出了这样的字符串:

{"Code":1,"Message":"This is just a test"} 

我想这个字符串,事后解析它,我想用JsonSplunker 。之后的研究时间,最引人注目的样品会是这样:

import groovyx.net.http.RESTClient 

def client = new RESTClient('http://www.acme.com/') 
def resp = client.get(path : 'products/3322') // ACME boomerang 

assert resp.status == 200 // HTTP response code; 404 means not found, etc. 
println resp.getData() 

(从这里取:http://rest.elkstein.org/2008/02/using-rest-in-groovy.html

但是它不承认import groovyx.net.http.RESTClient。你可以尝试在提供的groovy web sonsole中测试它,你会得到错误。

我试过import groovyx.net.http.RESTClient.*但仍然没有成功。

+1

您可能不需要使用外部JSON解析器。似乎'groovyx.net.http.RESTClient'返回已经解析了JSON的'response.data'对象。尝试使用'response.data.keySet()'获取顶级密钥列表。然后'response.data.blah'返回一个特定的键值。 – MarkHu

+0

@MarkHu感谢您的评论!我正在使用JsonSlurper,它工作。解析: inputedMemberID == resultMap [“MemberID”](例如) –

回答

3

Here is a simple Groovy script将HTTP POST发送到在线服务器并使用JsonSlurper解析响应。

此脚本可以在您的计算机上独立运行;它可能不适用于在线Groovy REPL。它使用Apache HTTPClient jar,它通过@Grab添加到类路径中。

对于一个项目,人们不会使用这种方法,而是将jar添加到Gradle中的类路径中。

+0

谢谢!有效。 JFYI,这个方法也可以工作:def html =“http://google.com”.toURL()。text。我需要它一个GET方法,但我把你的脚本,并适应它。很可能我将来可能需要帮助,所以我会在这里放下问题。我需要熟悉groovy :-) –

2

如果您的问题是与导入groovyx.net.http.RESTClient,那么你错过了依赖org.codehaus.groovy.modules.http-builder:http-builder

如果您只处理独立的Groovy脚本,则可以使用Groovy的Grape来获取依赖关系。下面是从RESTClienthome page一个例子:

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7') 
@Grab('oauth.signpost:signpost-core:1.2.1.2') 
@Grab('oauth.signpost:signpost-commonshttp4:1.2.1.2') 

import groovyx.net.http.RESTClient 
import static groovyx.net.http.ContentType.* 

def twitter = new RESTClient('https://api.twitter.com/1.1/statuses/') 
// twitter auth omitted 

try { // expect an exception from a 404 response: 
    twitter.head path: 'public_timeline' 
    assert false, 'Expected exception' 
} 
// The exception is used for flow control but has access to the response as well: 
catch(ex) { assert ex.response.status == 404 } 

assert twitter.head(path: 'home_timeline.json').status == 200 

如果您的Web应用程序使用依赖系统,如摇篮,那么你可以用它代替@Grab

+0

@Grab不起作用,它给了我一个sintax错误。这可能是由于我在开发脚本的web应用程序所获得的限制因素。但下面的答案帮助了我,现在一切都好了。谢谢你的回答,这里是你的投票,感谢你的叹息。 :-) –