Java Network Programming 筆記(3)

來源:互聯網
上載者:User

Java Network Programming 筆記
n5
三 利用URL類擷取資料
chapter 7 Retrieving Data with URLs
1 建立URL對象
當JVM不支援url的協議時拋出MalformedURLException
(1)public URL(String url) throws MalformedURLException
(2)public URL(String protocol, String hostname, String file) throws MalformedURLException
此構造器設定port為-1,所以協議的預設連接埠將被使用。
file參數應該以"/"開始,包含一個路徑,檔案名稱,和一個可選的錨點
例如: URL u = new URL("http","www.eff.org","/blueribbon.html#intro") ;
(3)public URL(String protocol,String host, int port, String file) throws MalformedURLException
可以指定連接埠,其他和第二個構造器相同
(4)public URL(URL base,String relative) throws MalformedURLException
從一個相對的URL地址和一個base URL對象建立一個絕對URL對象
例如:
try{
 URL u1 = new URL("http://www.myweb.com/java/index.html") ;
 URL u2 = new URL(u1,"test.html") ;
}
catch(MalformedURLException e){}
去掉u1的檔案名稱,然後加上新檔案名稱test.html,就構成了u2
2得到URL的組成
getFile() 返回總的路徑(並非檔案名稱)即為URL中從第一個"/"開始到"#"為止的內容。如果沒有file部分,java1.3返回一個Null 字元串,java1.1,1.2返回"/"
getHost() 返回主機名稱,不包含user:user這樣的使用者資訊
getPort() 如果URL中沒指定連接埠,則返回-1
getProtocol()
getRef() 返回指定的錨點,如果沒有錨點返回null
//since java1.3
getQuery()
getPath() 和getFile()完全相同
getUserInfo()
getAuthority()
3 從URL得到資料
(1) public final InputStream openStream() throws IOException
開啟URL,得到一個InputStream得到資料
(2) public URLConnection openConnection() throws IOException
開啟URL,得到一個URLConnection對象,URLConnection對象表示網路資源的一個開放串連。當想要直接與伺服器通訊時可使用該方法。URLConnection可以得到伺服器發送的任何東西,而不僅僅是文檔本身。而且還可以寫資料。
(3) public final Object getContent() throws IOException
將從URL下載來的資料看作一個對象,比如圖片,文本,聲音,或一個InputStream對於不能理解的對象。可以用instance of判斷到底是哪種對象,並cast為該對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.