Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤和異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java API 和框架

Java 類參考

Java 有用資源

Java - URL getProtocol() 方法及示例



描述

Java URL getProtocol() 方法返回與此 URL 關聯的協議。

宣告

以下是 java.net.URL.getProtocol() 方法的宣告

public String getProtocol()

引數

返回值

此 URL 的協議。

異常

示例 1

以下示例演示了對於具有 https 協議的有效 url 使用 Java URL getProtocol() 方法。在此示例中,我們正在建立 URL 類的例項。現在使用 getProtocol() 方法,我們獲取協議並列印它。

package com.tutorialspoint;

import java.io.IOException;
import java.net.URL;

public class UrlDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("https","www.tutorialspoint.com","/index.htm");
         String result = url.getProtocol();
         System.out.println(result);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上面的程式,這將產生以下結果:

輸出

https

示例 2

以下示例演示了對於具有 http 協議的有效 url 使用 Java URL getProtocol() 方法。在此示例中,我們正在使用埠號 80 建立 URL 類的例項。現在使用 getProtocol() 方法,我們獲取協議並列印它。

package com.tutorialspoint;

import java.io.IOException;
import java.net.URL;

public class UrlDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("http","www.tutorialspoint.com",80,"/index.htm");
         String result = url.getProtocol();
         System.out.println(result);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上面的程式,這將產生以下結果:

輸出

http

示例 3

以下示例演示了對於具有 file 協議的有效 url 使用 Java URL getProtocol() 方法。在此示例中,我們正在建立 URL 類的例項。現在使用 getProtocol() 方法,我們獲取協議並列印它。

package com.tutorialspoint;

import java.io.IOException;
import java.net.URL;

public class UrlDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("file","www.tutorialspoint.com","/index.htm");
         String result = url.getProtocol();
         System.out.println(result);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上面的程式,這將產生以下結果:

輸出

file
java_url.htm
廣告
© . All rights reserved.