2014-10-20 223 views
8

我正在學習一個名爲geoscript-groovy的腳本包的groovy。我跟着時髦REST教程here和測試下面的代碼:Groovy:無法解決類groovyx.net.http.RESTClient

import groovyx.net.http.RESTClient 

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

不過,我在import聲明得到了一個錯誤說:

Groovy:unable to resolve class groovyx.net.http.RESTClient 

我,四處搜尋,有很多的問題和答案對於此錯誤消息,例如,import groovyx.net.http.RESTClient in Groovy classRestClient Grails Import fails。然而,他們都是爲了Grails的,我不使用它,也不是很熟悉。

我的問題是

我應該如何解決這個錯誤,如果我只有groovy? (我的版本的groovy使用以下命令安裝在Ubuntu 12.04下)。

sudo apt-add-repository ppa:groovy-dev/groovy 
sudo apt-get update 
sudo apt-get install groovy 

謝謝。

- 編輯---

我加入建議@Grab陳述,並提出了一個兩行rest1.groovy文件,如下所示:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7') 
import groovyx.net.http.RESTClient 

groovyConsole rest1.groovy似乎運行正常。但groovysh < rest1.groovy仍然給我一個錯誤(如下所示)。我想我需要在類似groovysh的環境中運行,因爲groovy腳本在後臺被稱爲Web服務。沒有@Grab行,該服務會生成一個異常。隨着@Grab線,該服務甚至不會註冊。是否有一種比每個腳本抓取包含groovyx.net.http.RESTClient的必要依賴關係更持久的方法(例如apt-get或手動複製某些內容)?

groovysh < rest1.groovy 
Groovy Shell (1.8.6, JVM: 1.7.0_72) 
Type 'help' or '\h' for help. 
------------------------------------------------------------------------------- 
groovy:000> @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7') 
groovy:001> import groovyx.net.http.RESTClient 
ERROR org.codehaus.groovy.tools.shell.CommandException: 
Invalid import definition: 'import groovyx.net.http.RESTClient'; reason: startup failed: 
script1413902882282760571375.groovy: 1: unable to resolve class groovyx.net.http.RESTClient 
@ line 1, column 1. 
    import groovyx.net.http.RESTClient 
+0

你在你的類路徑中包含http-builder嗎? 看看這個例子。 http://groovy.codehaus.org/modules/http-builder/doc/rest。html – Raphael 2014-10-20 23:10:27

回答

12

你可能只需要在葡萄行正常,確保你的Groovy腳本有你在classpath中需要的罐子。把它放在腳本的頂部:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7') 

注意,我看不到腳本的其餘部分,因此可能還有其他模塊需要抓取。 檢查這裏更多的可能性: http://groovy.codehaus.org/modules/http-builder/doc/rest.html

編輯

好,很高興現在它工作的方式的一部分。就groovysh而言,我不知道如何讓groovysh動態地獲得依賴庫,所以您真正需要做的是,作爲腳本安裝的一部分,還將需要的jar放在一個目錄中(調用從這個 groovysh -cp ./lib < script.groovy :通過行家使用http://groovy.codehaus.org/Groovy+Shell

你想應該是可用的罐子它「LIB」或類似),然後將參數添加到您的通話groovysh來自@Grab行的工件規範。

+1

感謝您的建議。它適用於「groovyConsole」,但不適用於「groovysh」。請看我的編輯。 – tinlyx 2014-10-21 14:58:56