gpt4 book ai didi

java - 检查 URL 在 Android 中是否有效而不捕获异常?

转载 作者:行者123 更新时间:2023-11-29 07:16:26 25 4
gpt4 key购买 nike

看,我必须检查 50 多个 URL 的有效性,我假设捕获超过 50 个异常有点过头了。有没有一种方法可以检查一堆 URL 是否有效,而无需将其包装在 try catch 中以捕获异常?另外,仅供引用,在 Android 中,类“UrlValidator”不存在(但它确实存在于标准 java 中),并且有 UrlUtil.isValidUrl(String url) 但该方法似乎对您向它抛出的任何内容感到满意只要它包含 http://... 有什么建议吗?

最佳答案

此解决方案确实会捕获异常,但其他人可能会发现它很有用并且不需要任何库。

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;
}
}

关于java - 检查 URL 在 Android 中是否有效而不捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9248792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com