什麼是 MalformedURLException 以及如何在 Java 中修復它?


在使用 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.tw/";
      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.tw/";
      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

更新於: 2020-07-02

18K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告