如何在 Java 中处理 MalformedURLException?
在使用 Java(JSE)进行客户端-服务器编程时,如果在程序中使用 java.net.URL 类对象,则需要通过传递表示所需 URL 的字符串来实例化此类,以便建立连接。如果传递的字符串中的 URL 无法解析或缺少合法的协议,则会生成 MalformedURLException。
示例
在以下 Java 示例中,我们尝试建立与页面的连接并发布响应。
我们修改了协议部分,将其更改为 htt,而它应该是 http 或 https。
import java.util.Scanner; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetExample { public static void main(String[] args) throws IOException { String url = "ht://tutorialspoint.com/"; 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()); } } }
运行时异常
Exception in thread "main" java.net.MalformedURLException: unknown protocol: htt at java.net.URL.<init>(Unknown Source) at java.net.URL.<init>(Unknown Source) at java.net.URL.<init>(Unknown Source) at myPackage.HttpGetExample.main(HttpGetExample.java:11)
处理 MalformedURLException
解决此问题的唯一方法是确保传递的 URL 是合法的,并具有正确的协议。
最好的方法是在继续执行程序之前验证 URL。对于验证,可以使用正则表达式或提供 URL 验证器的其他库。在以下程序中,我们使用异常处理本身来验证 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 HttpGetExample { 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 { String url = "ht://tutorialspoint.com/"; 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 valid URL
广告