I'm connecting to a simple RSS feed using HTTPUrlConnection. It works perfectly. I'd like to add a timeout to the connection since I don't want my app hanging in the event of a bad connection or whatever. This is the code I use and the setConnectTimeout method doesn't have any effect whatsoever.
HttpURLConnection http = (HttpURLConnection) mURL.openConnection(); http.setConnectTimeout(15000); //timeout after 15 seconds ...
If it helps I'm developing on android.
Connection timeout means response timeout of any JDBC call invoking data transmission over a connection socket. If the response message is not received within the time specified, an I/O exception is thrown. The JDBC standard (2.0/3.0) does not support setting of the connection timeout.
setConnectTimeout. public void setConnectTimeout(int timeout) Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. If the timeout expires before the connection can be established, a java. net.
URLConnection is an abstract class whose subclasses form the link between the user application and any resource on the web. We can use it to read/write from/to any resource referenced by a URL object. There are mainly two subclasses that extend the URLConnection class.
You should try to set the read timeout as well (http.setReadTimeout()
). Oftentimes, a web server will happily accept your connection, but it might be slow in actually responding to the request.
You probably either/both:
1) Don't read anything from connection
2) Don't catch & handle the exception properly
As mentioned here, use logic similar to this:
int TIMEOUT_VALUE = 1000; try { URL testUrl = new URL("http://google.com"); StringBuilder answer = new StringBuilder(100000); long start = System.nanoTime(); URLConnection testConnection = testUrl.openConnection(); testConnection.setConnectTimeout(TIMEOUT_VALUE); testConnection.setReadTimeout(TIMEOUT_VALUE); BufferedReader in = new BufferedReader(new InputStreamReader(testConnection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { answer.append(inputLine); answer.append("\n"); } in.close(); long elapsed = System.nanoTime() - start; System.out.println("Elapsed (ms): " + elapsed / 1000000); System.out.println("Answer:"); System.out.println(answer); } catch (SocketTimeoutException e) { System.out.println("More than " + TIMEOUT_VALUE + " elapsed."); }
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