How to check if URL is blocked by my firewall

Nemin picture Nemin · Aug 12, 2014 · Viewed 11.8k times · Source

I am trying to check if the URL is accessible or not. I am using HttpURLConnection for it. This is now I am implementing it.

public static boolean isUrlAccessible(final String urlToValidate)
            throws WAGException {
        URL url = null;
        HttpURLConnection huc = null;
        int responseCode = -1;
        try {
            url = new URL(urlToValidate);
            huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            responseCode = huc.getResponseCode();
        } catch (final UnknownHostException e) {
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } catch (final MalformedURLException e){
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } catch (ProtocolException e) {
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } finally {
            if (huc != null) {
                huc.disconnect();
            }
        }
        return responseCode == 200;
    }

When the Internet is down it throws an UnknownHostException, I wanted to know how do I check if a fire wall is blocking a URL and thats why I get an exception and not because that the URL is not accessible. Also, I am just checking for response code 200 to make sure that the URL is accessible. Are there any other checks I need to perform?

Answer

user207421 picture user207421 · Aug 12, 2014

When the Internet is down it throws an UnknownHostException

No, it throws that when the DNS is down or the host isn't known to DNS.

I wanted to know how do I check if a fire wall is blocking a URL

You will get a connect timeout. In rare cases with obsolete hardware you may get a connection refusal, but I haven't heard of that this century. But you will also get a connect timeout if the host is down.

I am just checking for response code 200 to make sure that the URL is accessible. Are there any other checks I need to perform?

No. But URLs aren't blocked by firewalls. Ports are blocked by firewalls.