2016-08-27 97 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應用程序所獲得的限制因素。但下面的答案幫助了我,現在一切都好了。謝謝你的回答,這裏是你的投票,感謝你的嘆息。 :-) –