I'm using the following code to get a JSON string from a URL:
public static String getStringFromURL(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
org.apache.commons.io.IOUtils.copy(url.openStream(), output);
return output.toString();
}
I want to make sure this doesn't hang if the page at "addr" fails for any reason. I don't want it to bring our server down or anything. We started looking into how java.net.URL opens the connection and couldn't tell much from the Javadoc (we are using 1.5). Any thoughts or inside knowledge would be appreciated. If you can cite sources, so much the better. Thanks!
Technically, that depends on the protocol. For HTTP, it uses TCP/IP sockets. The openStream() will throw an exception if an I/O error occurs. Just put it in a try/catch. However, if the server returns for example a HTTP 404 (not found) or 500 (internal error), you will get this plain into the string unawarely. You may want to use HttpURLConnection instead for more fine-grained control.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseStatus() == 200) {
// All OK, convert connection.getInputStream() to string.
// Don't forget to take character encoding into account!
} else {
// Possible server error. Throw exception yourself? Or return some default?
}
Further you can set the timeout URLConnection#setConnectTimeout(). I believe, it defaults to 3 seconds or something. You may want to tweak it to make it all faster. Set with 1000 for 1 second.
Yes, it will hang.
There are two timeouts to consider:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With