How does java.net.URL open a connection? Does it use a socket?
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()