gpt4 book ai didi

java - 如何在 Apache HttpClient 4.5 中设置默认超时? (流利)

转载 作者:行者123 更新时间:2023-11-29 07:27:17 25 4
gpt4 key购买 nike

我在 Java 控制台应用程序中使用 Apache HttpClient 4.5(具有流畅的界面)。我注意到,它的默认超时值似乎是无限的,但我必须为我发送的请求使用非无限的超时值。我想对所有请求使用相同的超时值。

我如何全局设置默认的连接超时和套接字超时值,这样我就不必在发送请求的代码中的每个地方都设置它们?(记得我用的是流畅的界面)


示例:

现在,我发送请求的代码中的每个地方我都会做类似的事情:(简单示例)

HttpResponse response = Request.Get(url)
.connectionTimeout(CONNECTION_TIMEOUT) // <- want to get rid of this
.sessionTimeout(SESSION_TIMEOUT) // <- and this
.execute()
.returnResponse();

我想做的是在我的程序开始时一劳永逸地设置默认值。像这样的东西:

SomeImaginaryConfigClass.setDefaultConnectionTimeout(CONNECTION_TIMEOUT);
SomeImaginaryConfigClass.setDefaultSessionTimeout(SESSION_TIMEOUT);

这样我就可以像这样发送一个请求

HttpResponse response = Request.Get(url).execute().returnResponse();

无需在每次调用时都设置超时参数。

我在网上看到了一些答案,但它们要么是针对旧版本的 Apache HttpClient(即不起作用),要么是谈论使用构建器或传递配置类或其他方法太复杂为了我的需要。我只想设置默认的超时值,没有比这更好的了。我在哪里做这个?

最佳答案

可以使用自定义的 Executor 来做到这一点

RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(5000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setDefaultSocketConfig(socketConfig)
.build();

Executor executor = Executor.newInstance(client);
executor.execute(Request.Get("http://thishost/")).returnResponse();
executor.execute(Request.Get("http://thathost/")).returnResponse();

关于java - 如何在 Apache HttpClient 4.5 中设置默认超时? (流利),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49561248/

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