java net ---------------------------URL類
package java_net; import java.net.MalformedURLException; import java.net.URL; /* * 測試URL類 */ public class URL_Test { public static void main(String[] args) { try { //我們需要構造一個URL對象,構造方法有很多種 /* * 1、通過一個字符串構造URL對象 * public URL(String spec) throws MalformedURLException * Creates a URL object from the String representation. * This constructor is equivalent to a call to the two-argument constructor with a null first argument. * Parameters: * spec - the String to parse as a URL.(參數spec是一個可以代表網絡地址的字符串) */ URL url1 = new URL("http://www.baidu.com"); System.out.println(url1.getAuthority()); /* * Gets the protocol name of this URL * 返回協議的名稱 */ System.out.println("協議爲:"+url1.getProtocol());//輸出HTTP協議 /* * Gets the host name of this URL * 返回URL主機的名稱 */ System.out.println("主機爲:"+url1.getHost()); /* * Gets the path part of this URL. * 獲取該URL地址的部分路徑,如果不存在則爲Null */ System.out.println(url1.getPath()); /* * Gets the file name of this URL. * 獲取該地址的文件名稱,未指定文件時則輸出Null */ System.out.println(url1.getFile()); /* * Gets the anchor (also known as the "reference") of this URL. * Returns:the anchor (also known as the "reference") of this URL, or null if one does not exist * 返回錨點的值,不存在則爲空 */ System.out.println(url1.getRef()); /* * Gets the port number of this URL. * 獲取端口號,未設置則輸出-1 */ System.out.println("端口號爲:"+url1.getPort()); /* * Gets the default port number of the protocol associated with this URL. * If the URL scheme or the URLStreamHandler for the URL do not define a default port number, * then -1 is returned. * 返回協議默認的端口號,如果協議未定義端口號,返回-1 */ System.out.println(url1.getDefaultPort()); } catch (MalformedURLException e) { e.printStackTrace(); } } }
查看URL還有其他的方法,用時查閱API即可!
實例:
package java_net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; /* * 通過URL在網絡中讀取數據 * 讀取www.baidu.com主頁 */ public class URL_Test02 { public static void main(String[] args) { try { //創建URL對象 URL url = new URL("https://www.baidu.com"); //獲取URL對象的字節輸入流 InputStream is = url.openStream(); //將字節輸入流包裝成字符輸入流,注意要指定字符集 InputStreamReader isr = new InputStreamReader(is,"utf-8"); //將字符輸入流包裝成緩衝字符輸入流 BufferedReader br = new BufferedReader(isr); //進行數據的讀取 String line = br.readLine(); //循環讀取數據 while(line!=null){ //打印讀取到的數據 System.out.println(line); //再次讀取 line = br.readLine(); } //關閉輸入流 br.close(); isr.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }