如何让HttpURLConnection超时?

问题描述 投票:0回答:1

我继承的代码使用

HttpURLConnection
连接到 Apache 托管的 Perl 脚本以获取一些数据。我想让请求在 2 秒后超时,然后在日志中打印一条消息。

我在 Perl 中放置了一个

sleep 10
命令,这使得 Perl 脚本延迟 10 秒。然而,尽管将
HttpURLConnection
的超时设置为 1 毫秒,它仍然收到来自 Perl 的请求,忽略我的超时设置。

我做错了什么?这是我的代码,简化为我希望的要点:

HttpURLConnection connection = (HttpURLConnection) new URL(URLDecoder.decode(url)).openConnection();
connection.setConnectTimeout(1) ;
output = connection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
bufferedWriter.write(sb.toString());/* the request */
bufferedWriter.close();
output.close();
try {
    InputStream res = connection.getInputStream();
    writer = new StringWriter();
    IOUtils.copy(res, writer, "ISO-8859-1");
}
catch(java.net.SocketTimeoutException e)    {
    logger.debug("CONNECTION TIMED OUT");
}
return writer.toString(); // the returned data returned to calling function

我有两个问题:

我只是希望这不起作用。我已将连接超时设置为 1 毫秒。 Perl(肯定)休眠了 10 秒。其次,我期望捕获超时错误。

java httpurlconnection
1个回答
3
投票

我相信

connectTimeout
仅适用于连接本身,即握手完成之前的时期。对于等待服务器发送内容超时,尝试
connection.setReadTimeout(1000);

© www.soinside.com 2019 - 2024. All rights reserved.