Setting the Read Timeout on a URL Request in Java
I got a request from a co-worker late yesterday to add in a timeout to the AJAX gathering code in my web app. It wasn't immediately obvious, but I spent just a few minutes and it turned out to be pretty simple after all. It's used when you need to pull in an XML file from a URL for parsing into a DOM. Not hard, but very important to get right, and in a nicely flexible way.
If you start with the code I had originally:
InputSource retval = null; URL source = ...; try { retval = new InputSource(new InputStreamReader(source.openStream())); } catch (IOException ioe) { if (!ioe.getMessage().equals("Connection refused") && !ioe.getMessage().startsWith("Server returned HTTP response code: 500 ")) { log.error("While trying to get the data from the URL, an IOException occurred: " + ioe.getMessage(); } }
and then finally read in the JavaDocs that the call:
source.openStream()
is really just:
source.openConnection().getInputStream()
So the code can quickly become:
InputSource retval = null; URL source = ...; try { URLConnection conn = source.openConnection(); if (conn != null) { if (aTimeoutMSec > 0) { conn.setReadTimeout(aTimeoutMSec); } retval = new InputSource(new InputStreamReader(conn.getInputStream())); } } catch (IOException ioe) { if (!ioe.getMessage().equals("Connection refused") && !ioe.getMessage().startsWith("Server returned HTTP response code: 500 ")) { log.error("While trying to get the data from the URL, an IOException occurred: " + ioe.getMessage(); } }
In the end, we added in more logging - even a stack trace by a co-worker to help them find out what the problem was with a server-side error. But I have to admit, Java isn't as clear as it could be on things like this. But the JavaDocs did have what I needed, and that was enough to find out what I needed.