在Java中,Java.net包里面的類是進行網絡編程的,其中,java.net.URL類和java.net.URLConection類是編程者方便地利用URL在Internet上進行網絡通信。有兩種方法可以用來訪問Internet。
一是使用URL類的openStream()方法:
openStream()方法與制定的URL建立連接並返回InputStream類的對象,以從這一連接中讀取數據;
openStream()方法只能讀取網絡資源。
二是使用URL類的openConnection()方法:
openConnection()方法會創建一個URLConnection類的對象,此對象在本地機和URL指定的遠程節點建立一條HTTP協議的數據通道,可進行雙向數據傳輸。類URLConnection提供了很多設置和獲取連接參數的方法,最常用到的是getInputStream()和getOutputStream()方法。
openConnection()方法既能讀取又能發送數據。
下面通過兩個例子分別介紹兩種方法:
1.openStream()方法訪問Internet
下面的例子實現了訪問http://www.baidu.com,獲取其html代碼:
public class URLTest2 { public static void main(String args[]) throws Exception { try { URL url = new URL("http://www.baidu.com"); InputStream in =url.openStream(); InputStreamReader isr = new InputStreamReader(in); BufferedReader bufr = new BufferedReader(isr); String str; while ((str = bufr.readLine()) != null) { System.out.println(str); } bufr.close(); isr.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
上例首先創建對象url,並通過url.openStream()方法打開輸入流獲取InputStreamReader對象,再由此對象創建BufferedReader對象bufr,從bufr中讀取數據即可得到url所指定的資源文件。
2.openConnection()方法訪問Internet
下面的例子實現了訪問http://www.baidu.com,獲取其html代碼:
public class URLTest { public static void main(String[] args) { try { URL url = new URL("http://www.baidu.com"); URLConnection URLconnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) URLconnection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.err.println("成功"); InputStream in = httpConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(in); BufferedReader bufr = new BufferedReader(isr); String str; while ((str = bufr.readLine()) != null) { System.out.println(str); } bufr.close(); } else { System.err.println("失敗"); } } catch (Exception e) { e.printStackTrace(); } } }
上例首先創建對象url,並通過url.openConnection()方法獲取URLConnection對象,並轉換成HttpURLConnection對象,再由此對象的getInputStream()方法打開輸入流獲取InputStreamReader對象,然后由此對象創建BufferedReader對象bufr,從bufr中讀取數據即可得到url所指定的資源文件。