HttpURLConnection getResponseCode () deos is not returned if there is no internet connection

I use HttpURLConnection to check if the server url is accessible using the following code:

 try { boolean connectionFailed = false; URL knownURL = new URL("http://www.google.com"); httpConnection = (HttpURLConnection) knownURL.openConnection(); httpConnection.setConnectTimeout(5000); responseCode = httpConnection.getResponseCode(); if (responseCode != 200) { status = ConnectionStatus.NOT_CONNECTED; } } catch(Exception e) { connctionFailed = true; } 

This code works fine under normal conditions. But when there is no Internet connection (since either the router is disconnected or there is no access point), httpConnection.getResponseCode() fails (the function does not return). How can i fix this?

+6
source share
2 answers

httpConnection.setConnectTimeout(5000) is the timeout for the connection.

This is not a timeout for httpConnection.getResponseCode() .

If you add httpConnection.setReadTimeout(2000) , httpConnection.getResponseCode() should throw an exception if the connection is not available.

+4
source

You may have a higher level catch try block that throws a sockettimeout exception.

0
source

Source: https://habr.com/ru/post/977630/


All Articles