如何使用Groovy访问网页?

use*_*051 1 groovy

我尝试使用 Groovy 连接到网页,

我尝试过这个,当 URL 为www.google.fr

String.metaClass.browse {
def handler = [(~/^Mac OS.*/)  : { "open $it".execute() }, (~/^Windows.*/) : { "cmd /C start $it".execute() },
(~/.*/)         : {
//--- assume Unix or Linux                        
def browsers = [ 'firefox'.'chrome' ]
//--- find a browser we know the location of
def browser = browsers.find {
"which $it".execute().waitFor() == 0
}
//--- and run it if one found
if( browser )
"$browser $it".execute()
}
]
def k = handler.find { k, v -> k.matcher( System.properties.'os.name' ).matches() }
k?.value( delegate )
}
www.google.fr".browse.()
Run Code Online (Sandbox Code Playgroud)

如果我输入下载文件的 URL,则会抛出编译错误。感谢您的帮助。

tim*_*tes 5

如果你想将它作为方法添加到 String 类中,你可以这样做:

String.metaClass.browse = { -> 
    java.awt.Desktop.desktop.browse(new URI(delegate))
}
Run Code Online (Sandbox Code Playgroud)

然后打电话

"http://www.google.com".browse()
Run Code Online (Sandbox Code Playgroud)

将打开您的默认浏览器