java如何使HttpURLConnection超时?
我继承的代码使用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秒。然后,第二,我希望捕获一个超时错误
# 1 楼答案
我相信
connectTimeout
只适用于连接本身,即握手完成之前的时间段。等待服务器发送内容超时,请尝试connection.setReadTimeout(1);