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

查看:77
本文介绍了在 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 denied"异常.

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.

推荐答案

为了社区的利益,因为这个帖子在搜索时在 Google 上名列前茅
"url 验证器 java"

捕获异常代价高昂,应尽可能避免.如果您只想验证您的字符串是否是有效的 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天全站免登陆