简体   繁体   English

如何在android中检查URL的可用性

[英]How can I check the availability of an URL in android

My question is how I can check the availability of an URL:我的问题是如何检查 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每次都返回false

The following code use the core Java implementation for checking if a link is accessible.以下代码使用核心 Java 实现来检查链接是否可访问。 It should be adaptable to Android.它应该适用于Android。 Remember that the URL should be completed, ie with scheme, host name, otherwise an exception is thrown.记住URL要填写完整,即有scheme,主机名,否则抛出异常。

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.在Android中,上述方法可能由于两个原因而失败。

  1. The URL you are targeting is of http protocol instead of https.您定位的 URL 是 http 协议而不是 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. 2.您可能正在主线程中运行检查 url 代码。 Android prevent accessing network request in main thread. Android 防止在主线程中访问网络请求。 To solve this put your code in an AsyncTask or in a separate thread.要解决此问题,请将您的代码放在 AsyncTask 或单独的线程中。 The following code is just for illustration.以下代码仅用于说明。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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