Android 中如何检查 URL 是否有效

发布于 2024-10-16 03:21:44 字数 69 浏览 3 评论 0原文

有没有一种好方法可以避免导致应用程序崩溃的“主机未解析”错误?有某种方法可以尝试连接到主机(例如 URL)并查看它是否有效?

Is there a good way to avoid the "host is not resolved" error that crashes an app? Some sort of a way to try connecting to a host ( like a URL ) and see if it's even valid?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

风吹雨成花 2024-10-23 03:21:44

使用 URLUtil 验证 URL,如下所示。

URLUtil.isValidUrl(url)

如果 URL 有效,它将返回 true;如果 URL 无效,它将返回 false

Use URLUtil to validate the URL as below.

URLUtil.isValidUrl(url)

It will return true if URL is valid and false if URL is invalid.

烟酉 2024-10-23 03:21:44
URLUtil.isValidUrl(url);

如果这不起作用,您可以使用:

Patterns.WEB_URL.matcher(url).matches();
URLUtil.isValidUrl(url);

If this doesn't work you can use:

Patterns.WEB_URL.matcher(url).matches();
挽你眉间 2024-10-23 03:21:44

我将使用此处提到的方法和其他 Stackoverflow 线程中提到的方法的组合:

public static boolean IsValidUrl(String urlString) {
    try {
        URL url = new URL(urlString);
        return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
    } catch (MalformedURLException ignored) {
    }
    return false;
}

I would use a combination of methods mentioned here and in other Stackoverflow threads:

public static boolean IsValidUrl(String urlString) {
    try {
        URL url = new URL(urlString);
        return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
    } catch (MalformedURLException ignored) {
    }
    return false;
}
情魔剑神 2024-10-23 03:21:44

如果您使用 kotlin ,您可以创建一个 String.kt 并编写如下代码:

fun String.isValidUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches()

然后:

String url = "www.yourUrl.com"
if (!url.isValidUrl()) {
    //some code
}else{
   //some code
}

If you are using from kotlin you can create a String.kt and write code bellow:

fun String.isValidUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches()

Then:

String url = "www.yourUrl.com"
if (!url.isValidUrl()) {
    //some code
}else{
   //some code
}
酒中人 2024-10-23 03:21:44

只需添加这行代码:

Boolean isValid = URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches();       

Just add this line of code:

Boolean isValid = URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches();       
心舞飞扬 2024-10-23 03:21:44

将操作包装在 try/catch 中。有很多方法可以使 URL 格式良好但无法检索。此外,诸如查看主机名是否存在之类的测试并不能保证任何结果,因为在检查后主机可能会变得无法访问。基本上,再多的预检查也不能保证检索不会失败并抛出异常,因此您最好计划好处理异常。

Wrap the operation in a try/catch. There are many ways that a URL can be well-formed but not retrievable. In addition, tests like seeing if the hostname exists doesn't guarantee anything because the host might become unreachable just after the check. Basically, no amount of pre-checking can guarantee that the retrieval won't fail and throw an exception, so you better plan to handle the exceptions.

始终不够 2024-10-23 03:21:44

我尝试了很多方法。发现没有人可以很好地使用 此 URL:

现在我使用以下内容,一切顺利。

public static boolean checkURL(CharSequence input) {
    if (TextUtils.isEmpty(input)) {
        return false;
    }
    Pattern URL_PATTERN = Patterns.WEB_URL;
    boolean isURL = URL_PATTERN.matcher(input).matches();
    if (!isURL) {
        String urlString = input + "";
        if (URLUtil.isNetworkUrl(urlString)) {
            try {
                new URL(urlString);
                isURL = true;
            } catch (Exception e) {
            }
        }
    }
    return isURL;
}

I have tried a lot of methods.And find that no one works fine with this URL:

Now I use the following and everything goes well.

public static boolean checkURL(CharSequence input) {
    if (TextUtils.isEmpty(input)) {
        return false;
    }
    Pattern URL_PATTERN = Patterns.WEB_URL;
    boolean isURL = URL_PATTERN.matcher(input).matches();
    if (!isURL) {
        String urlString = input + "";
        if (URLUtil.isNetworkUrl(urlString)) {
            try {
                new URL(urlString);
                isURL = true;
            } catch (Exception e) {
            }
        }
    }
    return isURL;
}
与往事干杯 2024-10-23 03:21:44
import okhttp3.HttpUrl;
import android.util.Patterns;
import android.webkit.URLUtil;

            if (!Patterns.WEB_URL.matcher(url).matches()) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (HttpUrl.parse(url) == null) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (!URLUtil.isValidUrl(url)) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (!url.substring(0,7).contains("http://") & !url.substring(0,8).contains("https://")) {
                error.setText(R.string.wrong_server_address);
                return;
            }
import okhttp3.HttpUrl;
import android.util.Patterns;
import android.webkit.URLUtil;

            if (!Patterns.WEB_URL.matcher(url).matches()) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (HttpUrl.parse(url) == null) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (!URLUtil.isValidUrl(url)) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (!url.substring(0,7).contains("http://") & !url.substring(0,8).contains("https://")) {
                error.setText(R.string.wrong_server_address);
                return;
            }
妄想挽回 2024-10-23 03:21:44

就我而言,当我输入类似于“first.secondword”(我的应用程序)的String时,Patterns.WEB_URL.matcher(url).matches()无法正常工作检查用户输入)。该方法返回true。

URLUtil.isValidUrl(url) 对我来说工作正常。也许对其他人有用

In my case Patterns.WEB_URL.matcher(url).matches() does not work correctly in the case when I type String similar to "first.secondword"(My app checks user input). This method returns true.

URLUtil.isValidUrl(url) works correctly for me. Maybe it would be useful to someone else

伴我心暖 2024-10-23 03:21:44

您可以通过以下方式验证 URL:

Patterns.WEB_URL.matcher(potentialUrl).matches()

You cans validate the URL by following:

Patterns.WEB_URL.matcher(potentialUrl).matches()
三生殊途 2024-10-23 03:21:44
public static boolean isURL(String text) {
    String tempString = text;

    if (!text.startsWith("http")) {
        tempString = "https://" + tempString;
    }

    try {
        new URL(tempString).toURI();
        return Patterns.WEB_URL.matcher(tempString).matches();
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        return false;
    }
}

这是我正在使用的正确解决方案。在原始文本前添加 https:// 可防止“www.cats.com”等文本被视为 URL。如果 new URL() 成功,那么如果您只是检查模式以排除简单文本,例如“https://cats ”被视为URL

public static boolean isURL(String text) {
    String tempString = text;

    if (!text.startsWith("http")) {
        tempString = "https://" + tempString;
    }

    try {
        new URL(tempString).toURI();
        return Patterns.WEB_URL.matcher(tempString).matches();
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        return false;
    }
}

This is the correct sollution that I'm using. Adding https:// before original text prevents text like "www.cats.com" to be considered as URL. If new URL() succeed, then if you just check the pattern to exclude simple texts like "https://cats" to be considered URL.

独自←快乐 2024-10-23 03:21:44
new java.net.URL(String) throws MalformedURLException
new java.net.URL(String) throws MalformedURLException
余罪 2024-10-23 03:21:44
public static boolean isLink(String url) {
    // Regular expression to match a complete and valid URL
    String urlRegex = "\\b((http|https|ftp):\\/\\/[a-z0-9-]+(\\.[a-z0-9-]+)+([\\/?].*)?)\\b";
    Pattern urlPattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);

    if (url == null) {
        return false;
    }
    Matcher matcher = urlPattern.matcher(url);
    return matcher.matches();
}
public static boolean isLink(String url) {
    // Regular expression to match a complete and valid URL
    String urlRegex = "\\b((http|https|ftp):\\/\\/[a-z0-9-]+(\\.[a-z0-9-]+)+([\\/?].*)?)\\b";
    Pattern urlPattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);

    if (url == null) {
        return false;
    }
    Matcher matcher = urlPattern.matcher(url);
    return matcher.matches();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文