2014-10-20 196 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