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 开发者_如何学Pythonusing 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:
- The connection timeout: The server may neither accept (ACK) nor reject (RST) the connection because it is firewalled. This is rather short and can be set using setConnectTimeout();
- The timeout the connection waits for data. This one is rather long (5 minutes) and is the usual thing that fails, for example if the webapplication is waiting for a database connection from a pool. It can be set using setReadTimeout()
精彩评论