Groovy:向URL发送请求,忽略结果

Mar*_*itt 4 java groovy

在groovy中,有没有办法向URL发送请求,忽略响应?主要目的是在更短的时间内向服务器发送更多请求.

因为结果对我来说并不重要,一旦发送请求,我不希望脚本在继续之前等待响应.

这是我当前的脚本:

(1..50).each { element->
  def url = "http://someUrl"
  url.toURL().text 
} 
Run Code Online (Sandbox Code Playgroud)

在此代码中,该text方法必须加载整个响应,我并不真正关心.重要的是发送请求,等待响应并不重要.

有类似的send方法吗?(沿着...的路线

url.toURL().send
Run Code Online (Sandbox Code Playgroud)

或者,是否有一种"groovy"方式我可以使用GPARS并行运行循环来加快速度?

Jas*_*man 6

对于只发送URL,您可以使用withInputStreamwithReader方法发送请求而不读取文本.这将只创建一个处理程序来读取将立即关闭的传入文本.

至于GPars,你可以使用的组合withPool,并callAysnc创建一个线程池来并发执行的请求.例如:

@Grab(group='org.codehaus.gpars', module='gpars', version='0.12')
import static groovyx.gpars.GParsExecutorsPool.withPool

withPool(50) {
    50.times {
        Closure callUrl = {"http://google.com".toURL().withReader {}}
        callUrl.callAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您不关心线程数,则可以在没有GPars的情况下创建自己的线程.例如:

50.times { 
    Closure callUrl = {"http://google.com".toURL().withReader {}}
    Thread.start callUrl
}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定,但这不会留下50个开放的连接吗?不会'封闭callUrl = {"http://google.com".toURL().withReader {}}`会更好,因为它也会关闭连接吗? (2认同)