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 useHttpURLConnectioninstead for more fine-grained control.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 with1000for 1 second.