Groovy:无法解析类groovyx.net.http.RESTClient

时间:2014-10-20 22:00:14

标签: rest groovy

我正在为一个名为geoscript-groovy的脚本包学习groovy。我按照groovy REST教程here测试了以下代码:

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

1 个答案:

答案 0 :(得分:13)

您可能只需要Grape一行就可以正确地确保您的Groovy脚本在类路径中具有您需要的jar。把它放在脚本的顶部:

@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放在一个目录中(调用它“lib”或其他一些),然后将参数添加到您的groovysh调用: groovysh -cp ./lib&lt; script.groovy 从这个:http://groovy.codehaus.org/Groovy+Shell

你想要的jar应该可以通过maven使用@Grab行的工件规范获得。