【发布时间】:2009-12-03 11:45:11
【问题描述】:
我使用以下 Groovy sn-p 在 Grails 应用程序中获取 HTML 页面的纯文本表示:
String str = new URL("http://www.example.com/some/path")?.text?.decodeHTML()
现在我想更改代码,使请求在 5 秒后超时(导致str == null)。实现这一目标的最简单和最 Groovy 的方法是什么?
【问题讨论】:
我使用以下 Groovy sn-p 在 Grails 应用程序中获取 HTML 页面的纯文本表示:
String str = new URL("http://www.example.com/some/path")?.text?.decodeHTML()
现在我想更改代码,使请求在 5 秒后超时(导致str == null)。实现这一目标的最简单和最 Groovy 的方法是什么?
【问题讨论】:
您必须以旧方式进行,获取 URLConnection,在该对象上设置超时,然后通过 Reader 读取数据
这将是添加到 Groovy 的一件好事(恕我直言),因为我可以看到自己在某些时候需要它;-)
也许建议将其作为 JIRA 上的功能请求?
我已将其作为 RFE 添加到 Groovy JIRA
https://issues.apache.org/jira/browse/GROOVY-3921
所以希望我们能在 Groovy 的未来版本中看到它......
【讨论】:
我查看了 groovy 2.1.8 的源代码,以下代码可用:
'http://www.google.com'.toURL().getText([connectTimeout: 2000, readTimeout: 3000])
处理配置映射的逻辑位于方法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();
}
【讨论】: