Android 中如何检查 URL 是否有效
有没有一种好方法可以避免导致应用程序崩溃的“主机未解析”错误?有某种方法可以尝试连接到主机(例如 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
使用
URLUtil
验证 URL,如下所示。如果 URL 有效,它将返回
true
;如果 URL 无效,它将返回false
。Use
URLUtil
to validate the URL as below.It will return
true
if URL is valid andfalse
if URL is invalid.如果这不起作用,您可以使用:
If this doesn't work you can use:
我将使用此处提到的方法和其他 Stackoverflow 线程中提到的方法的组合:
I would use a combination of methods mentioned here and in other Stackoverflow threads:
如果您使用
kotlin
,您可以创建一个String.kt
并编写如下代码:然后:
If you are using from
kotlin
you can create aString.kt
and write code bellow:Then:
只需添加这行代码:
Just add this line of code:
将操作包装在 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.
我尝试了很多方法。发现没有人可以很好地使用 此 URL:
现在我使用以下内容,一切顺利。
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.
就我而言,当我输入类似于“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 typeString
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您可以通过以下方式验证 URL:
You cans validate the URL by following:
这是我正在使用的正确解决方案。在原始文本前添加
https://
可防止“www.cats.com”等文本被视为URL
。如果new URL()
成功,那么如果您只是检查模式以排除简单文本,例如“https://cats ”被视为URL
。This is the correct sollution that I'm using. Adding
https://
before original text prevents text like "www.cats.com" to be considered asURL
. Ifnew URL()
succeed, then if you just check the pattern to exclude simple texts like "https://cats" to be consideredURL
.