2009-12-03 52 views
6

我用下面的Groovy的片段,以获得一个Grails应用程序中的一个HTML页面的纯文本表示:设置超时时间为新的URL(...)在Groovy/Grails的文本

String str = new URL("http://www.example.com/some/path")?.text?.decodeHTML() 

现在我想修改代码,以便请求在5秒后超时(导致str == null)。什么是最简单,最Groovy的方式来实现呢?

回答

6

你不得不做旧的方式,获得一个URLConnection,设置该对象上超时,然后通过一个阅读器

读取数据这将是添加到常规虽好东西(因为它是我可以看到我自己需要在某个点上;-)

也许建议它作为JIRA上的功能请求?

我已经添加它作为Groovy的JIRA

http://jira.codehaus.org/browse/GROOVY-3921

一个RFE所以希望我们会看到它在Groovy的未来版本...

+0

+1:非常好!并且使用补丁:http://jira.codehaus.org/secure/attachment/46210/URL.text-timout.patch – knorv 2009-12-03 14:26:33

+0

希望我能想到一种测试方式,尽管(不需要测试机器具有互联网连接,而且每次有人运行测试时都不会敲击某个可怜的站点);-) – 2009-12-03 16:10:19

+1

只是一个更新,它已经在Groovy中发布。 返回新的URL(url).getText([connectTimeout:500,readTimeout:5000]); – Ben 2013-04-30 20:03:19

4

我检查源代码的常规2.1.8,下面代码是可用的:

String text = '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(); 
}