如何使用 Java 检测某个 URL 是否有效?
java.net 包的 URL 类表示一个 Uniform Resource Locator(统一资源定位符),用于指向万维网中的一个资源(文件或目录或引用)。
此类提供各种构造函数,其中一个构造函数接受一个 String 参数并构造 URL 类的对象。将 URL 传递给此方法时,如果您使用了未知协议或未指定任何协议,此方法将抛出 MalformedURLException。
类似地,此类的 toURI() 方法返回当前 URL 的 URI 对象。如果当前 URL 格式不正确或根据 RFC 2396 语法不正确,此方法将抛出 URISyntaxException。
在一个单独的方法中调用并通过字符串格式传递所需 URL 来创建 URL 对象,并调用 toURI() 方法。将此代码放到 try-catch 块中,如果抛出异常 (MalformedURLException 或 URISyntaxException),则表示给定的 URL 有问题。
示例
import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class ValidatingURL {
public static boolean isUrlValid(String url) {
try {
URL obj = new URL(url);
obj.toURI();
return true;
} catch (MalformedURLException e) {
return false;
} catch (URISyntaxException e) {
return false;
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter an URL");
String url = sc.next();
if(isUrlValid(url)) {
URL obj = new URL(url);
//Opening a connection
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//Sending the request
conn.setRequestMethod("GET");
int response = conn.getResponseCode();
if (response == 200) {
//Reading the response to a StringBuffer
Scanner responseReader = new Scanner(conn.getInputStream());
StringBuffer buffer = new StringBuffer();
while (responseReader.hasNextLine()) {
buffer.append(responseReader.nextLine()+"
");
}
responseReader.close();
//Printing the Response
System.out.println(buffer.toString());
}
}else {
System.out.println("Enter valid URL");
}
}
}输出
Enter an URL ht://tutorialspoint.com/ Enter valid URL
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP