gpt4 book ai didi

groovy - 使用 Groovy 的 HTTPBuilder,如何设置超时

转载 作者:行者123 更新时间:2023-12-04 19:01:54 45 4
gpt4 key购买 nike

我正在尝试使用 Groovy HTTPBuilder 设置连接超时,但我一生都找不到方法。

使用普通的 ol' URL 很容易:

def client = new URL("https://search.yahoo.com/search?q=foobar")
def result = client.getText( readTimeout: 1 )

这会引发 SocketTimeoutException,但这不是我想要的。出于各种原因,我宁愿使用 HTTPBuilder 或更好的 RESTClient。

这确实有效:
    def client = new HTTPBuilder()
def result = client.request("https://search.yahoo.com/", Method.GET, "*/*") { HttpRequest request ->
uri.path = "search"
uri.query = [q: "foobar"]
request.getParams().setParameter("http.socket.timeout", 1);
}

但是 request.getParams() 已被弃用。

对于我的一生,我找不到将适当的 RequestConfig 注入(inject)构建器的方法。

最佳答案

试试这个,我使用的是 0.7.1:

import groovyx.net.http.HTTPBuilder
import org.apache.http.client.config.RequestConfig
import org.apache.http.config.SocketConfig
import org.apache.http.conn.ConnectTimeoutException
import org.apache.http.impl.client.HttpClients

def timeout = 10000 // millis
SocketConfig sc = SocketConfig.custom().setSoTimeout(timeout).build()
RequestConfig rc = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build()
def hc = HttpClients.custom().setDefaultSocketConfig(sc).setDefaultRequestConfig(rc).build()
def http = new HTTPBuilder('https://search.yahoo.com/')
http.client = hc

http.get(path:'/search')

关于groovy - 使用 Groovy 的 HTTPBuilder,如何设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35636099/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com