如何使用 Java 检查 URL 是否有效?
java 8object oriented programmingprogramming
java.net 包中的 URL 类表示一个 Uniform Resource Locator,用于指向万维网上的资源(文件、目录或引用)。
此类提供各种构造函数,其中一个构造函数接受 String 参数并构造 URL 类的对象。将 URL 传递给此方法时,如果您使用了未知协议或未指定任何协议,则此方法将抛出 MalformedURLException。
类似地,此类的 toURI() 方法返回当前 URL 的 URI 对象。如果当前 URL 格式不正确或语法不符合 RFC 2396 要求,则此方法将抛出 URISyntaxException。
在单独的方法调用中,通过传递 Sting 格式的所需 URL 来创建 URL 对象,然后调用 toURI() 方法。如果抛出异常(MalformedURLException 或 URISyntaxException),表明给定的 URL 存在问题,则将此代码包装在 try-catch 块中。
示例
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); //打开连接 HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //发送请求 conn.setRequestMethod("GET"); int response = conn.getResponseCode(); if (response == 200) { //将响应读取到 StringBuffer Scanner responseReader = new Scanner(conn.getInputStream()); StringBuffer buffer = new StringBuffer(); while (responseReader.hasNextLine()) { buffer.append(responseReader.nextLine()+"
"); } responseReader.close(); //打印响应 System.out.println(buffer.toString()); } }else { System.out.println("Enter valid URL"); } } }
输出
Enter an URL ht://www.tutorialspoint.com/ Enter valid URL