如何使用 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.tw/
Enter valid URL

更新於:2019-09-09

2K+ 瀏覽

開啟你的 職業生涯

完成該課程即可獲得認證

開始
廣告
© . All rights reserved.