简体   繁体   中英

How can I check the availability of an URL in android

My question is how I can check the availability of an URL:

My code

  public boolean URLvalide(){

    String URL_CHECK = "testurl";

    try {
        URL url = new URL(URL_CHECK);
        URLConnection con = url.openConnection();
        con.connect();
        return true;
    } catch (MalformedURLException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

It returns false every time

The following code use the core Java implementation for checking if a link is accessible. It should be adaptable to Android. Remember that the URL should be completed, ie with scheme, host name, otherwise an exception is thrown.

public boolean checkURL () {
    try {
        URL myUrl = new URL("http://www.google.com");
        HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
        connection.connect();
        int statusCode = connection.getResponseCode();
        if (statusCode == HttpURLConnection.HTTP_OK) {
            System.out.println("Accessible");
        } else {
            System.out.println("Not-Accessible");
        }
    } catch (Exception e) {
        System.out.println("not-accessible");
    }
    }

Updated:

In Android, the above method may fail due to two reasons.

  1. The URL you are targeting is of http protocol instead of https. In this case you need to allow clear text traffic in your application manifest.

     <application> ... android:usesCleartextTraffic="true"

2.You might be running the check url code in your main thread. Android prevent accessing network request in main thread. To solve this put your code in an AsyncTask or in a separate thread. The following code is just for illustration.

Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            checkURL();
        }
    });
    backgroundThread.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM