ZimZim
ZimZim

Reputation: 3381

Check if URL is valid in Android without catching Exception?

See, I have to check like 50+ URLs for validity, and I'm assuming that catching more than 50 exceptions is kind of over the top. Is there a way to check if a bunch of URLs are valid without wrapping it in a try catch to catch exceptions? Also, just fyi, in Android the class "UrlValidator" doesn't exist (but it does exist in the standard java), and there's UrlUtil.isValidUrl(String url) but that method seems to be pleased with whatever you throw at it as long as it contains http://... any suggestions?

Upvotes: 1

Views: 5464

Answers (1)

William Pownall
William Pownall

Reputation: 770

This solution does catch exceptions, however others may find it useful and doesn't require any libraries.

public boolean URLIsReachable(String urlString)
{
    try
    {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        responseCode = urlConnection.getResponseCode();
        urlConnection.disconnect();
        return responseCode != 200;
    } catch (MalformedURLException e)
    {
        e.printStackTrace();
        return false;
    } catch (IOException e)
    {
        e.printStackTrace();
        return false;
    }
}

Upvotes: 7

Related Questions