gpt4 book ai didi

java - 手动超时java中的httpurlconnection

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

我已经尝试通过以下方式使 httpurlconnection 超时

URL urlConnect = new URL(url.toString());
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlc = (HttpURLConnection) urlConnect.openConnection();
urlc.setConnectTimeout(1000*5);
urlc.setReadTimeout(1000*5);
urlc.connect();

但无法连接,它采用 apache tomcat 指定的 2 分钟超时而不是我提供的 5 秒 g,在这种情况下如何手动超时 httpurlconnection

最佳答案

以下是 Java 手册对 connectTimeout 和 readTimeout 的说明:

连接超时

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.

读取超时

Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.

所以我认为在你的情况下,你设法在不到 5 秒的时间内建立了通信链接,并且你没有读取任何输入流。因此行为是正确的(等到 Apache 超时)

关于java - 手动超时java中的httpurlconnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14806330/

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