我使用以下Groovy代码段来获取Grails应用程序中HTML页面的纯文本表示:
String str = new URL("http://www.example.com/some/path")?.text?.decodeHTML()
Run Code Online (Sandbox Code Playgroud)
现在我想改变代码,以便请求在5秒后超时(导致str == null
).什么是最简单,最Groovy的方法来实现这一目标?
您必须以旧方式执行此操作,获取URLConnection,在该对象上设置超时,然后通过Reader读取数据
尽管(imho)添加到Groovy这是一件好事,因为这是我可以看到自己在某些时候需要的东西;-)
也许建议将其作为JIRA的功能请求?
我在Groovy JIRA上添加了它作为RFE
http://jira.codehaus.org/browse/GROOVY-3921
所以希望我们会在未来的Groovy版本中看到它......
我检查了groovy的源代码2.1.8
,以下代码可用:
'http://www.google.com'.toURL().getText([connectTimeout: 2000, readTimeout: 3000])
Run Code Online (Sandbox Code Playgroud)
处理配置图的逻辑位于方法中 org.codehaus.groovy.runtime.ResourceGroovyMethods#configuredInputStream
private static InputStream configuredInputStream(Map parameters, URL url) throws IOException {
final URLConnection connection = url.openConnection();
if (parameters != null) {
if (parameters.containsKey("connectTimeout")) {
connection.setConnectTimeout(DefaultGroovyMethods.asType(parameters.get("connectTimeout"), Integer.class));
}
if (parameters.containsKey("readTimeout")) {
connection.setReadTimeout(DefaultGroovyMethods.asType(parameters.get("readTimeout"), Integer.class));
}
if (parameters.containsKey("useCaches")) {
connection.setUseCaches(DefaultGroovyMethods.asType(parameters.get("useCaches"), Boolean.class));
}
if (parameters.containsKey("allowUserInteraction")) {
connection.setAllowUserInteraction(DefaultGroovyMethods.asType(parameters.get("allowUserInteraction"), Boolean.class));
}
if (parameters.containsKey("requestProperties")) {
@SuppressWarnings("unchecked")
Map<String, String> properties = (Map<String, String>) parameters.get("requestProperties");
for (Map.Entry<String, String> entry : properties.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
}
return connection.getInputStream();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4377 次 |
最近记录: |