The code I have inherited uses HttpURLConnection
to make a connection to a Perl script hosted by Apache to get some data. I want to make the request time out after, say 2 seconds, and print a message to the logs.
I have put a sleep 10
command in the Perl which makes the Perl script delay for 10 seconds. However despite having set the timeout on HttpURLConnection
to 1 millisecond, it still gets the request from Perl, ignoring my timeout setting.
What am I doing wrong? Here is my code, simplified to what I hope is the essential points:
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
I have two questions:
I am simply expecting this not to work. I have set the timeout on the connection to 1 millisecond. Perl is (definitely) sleeping for 10 seconds. And, then, secondly, I was expecting to catch a timeout error.
I believe the connectTimeout
applies only to the connection itself, i.e. the period before the handshake is completed. For timeout waiting for the server to send the content, try connection.setReadTimeout(1000);
.