在Java中验证URL [英] Validating URL in Java

查看:481
本文介绍了在Java中验证URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Java中是否有任何标准API来验证给定的URL?
我想检查URL字符串是否正确,即给定的协议是否有效,然后检查是否可以建立连接。

I wanted to know if there is any standard APIs in Java to validate a given URL? I want to check both if the URL string is right i.e. the given protocol is valid and then to check if a connection can be established.

我试过使用HttpURLConnection,提供URL并连接到它。我的要求的第一部分似乎已经完成但是当我尝试执行HttpURLConnection.connect()时,抛出'java.net.ConnectException:Connection refused'异常。

I tried using HttpURLConnection, providing the URL and connecting to it. The first part of my requirement seems to be fulfilled but when I try to perform HttpURLConnection.connect(), 'java.net.ConnectException: Connection refused' exception is thrown.

这可能是因为代理设置?我尝试为代理设置系统属性但没有成功。

Can this be because of proxy settings? I tried setting the System properties for proxy but no success.

让我知道我做错了什么。

Let me know what I am doing wrong.

推荐答案

为了社区的利益,因为在搜索

url validator java 时,此主题在Google上排名第一

For the benefit of the community, since this thread is top on Google when searching for
"url validator java"

捕获异常代价很高,应尽可能避免。如果您只想验证String是否是有效的URL,则可以使用 UrlValidator > Apache Commons Validator 项目。

Catching exceptions is expensive, and should be avoided when possible. If you just want to verify your String is a valid URL, you can use the UrlValidator class from the Apache Commons Validator project.

例如:

String[] schemes = {"http","https"}; // DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
   System.out.println("URL is valid");
} else {
   System.out.println("URL is invalid");
}

这篇关于在Java中验证URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆