1

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.

admdrew
  • 3,790
  • 4
  • 27
  • 39
  • 1
    possible duplicate of [HttpURLConnection setConnectTimeout() has no effect](http://stackoverflow.com/questions/6829801/httpurlconnection-setconnecttimeout-has-no-effect) – Virmundi Feb 14 '14 at 18:46

1 Answers1

2

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(1);.

BoppreH
  • 8,014
  • 4
  • 34
  • 71
  • Obviously with `1` you will always run into an exception. The value is interpreted as milliseconds, but I'm sure you already knew that... – hgoebl Feb 15 '14 at 09:12
  • Thanks. I haven't had a chance to test it yet. But based on the docs for that method that looks like just what I am looking for. –  Feb 25 '14 at 10:50