如何处理 Java 中的 MalformedURLException?

java 8object oriented programmingprogramming更新于 2025/4/26 17:52:17

在使用 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://www.tutorialspoint.com/";
      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());       }    } }

Runtime Exception

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://www.tutorialspoint.com/";
      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 valid URL

相关文章