java.net.URL類是標(biāo)準(zhǔn)資源定位符。每一個(gè)URL明確地指定了因特網(wǎng)上一個(gè)資源的位置。URL有四個(gè)構(gòu)造函數(shù),每一個(gè)都聲明了MalformedURLException
public URL(String u) throws MalformedURLException
public URL(String protocol, String host, String file) throws MalformedURLException
public URL(String protocol, String host, int port, String file) throws MalformedURLException
public URL(URL context, String u) throws MalformedURLException
如果構(gòu)造器沒有給定一個(gè)URL,MalformedURLException會(huì)被拋出。如果給你一個(gè)絕對(duì)的URL比如"http://www.itdecent.cn/u/9e21abacd418",你會(huì)這樣構(gòu)造一個(gè)URL對(duì)象:
URL u = null;
try {
u = new URL("http://www.itdecent.cn/u/9e21abacd418");
} catch (MalformedURLException e) {}
你也可以把協(xié)議,host和路徑分開傳入
URL u = null;
try {
u = new URL("http","www.itdecent.cn","/u/9e21abacd418");
} catch (MalformedURLException e) {}
一般情況下,你不需要特地指定協(xié)議的端口,大多數(shù)協(xié)議有他們默認(rèn)的端口,比如HTTP的協(xié)議的默認(rèn)端口是80.如果端口改變了,可以使用下面的構(gòu)造方法:
u = new URL("http","www.itdecent.cn",8080,"/u/9e21abacd418");
一旦URL對(duì)象被構(gòu)造,有兩種方式獲得它的內(nèi)容。openStream()方法返回原始的數(shù)據(jù)流,getContent()方法返回一個(gè)對(duì)象代表數(shù)據(jù)。當(dāng)你調(diào)用getContent()方法的時(shí)候,JAVA根據(jù)它的MIME類型,尋找一個(gè)content handler,然后返回一個(gè)可用的數(shù)據(jù)對(duì)象。
openStream()方法和URL代表的服務(wù)器和端口建立了一個(gè)Socket連接,返回一個(gè)可以獲取數(shù)據(jù)的InputStream,允許你從服務(wù)器上下載數(shù)據(jù)。所有的頭文件,跟數(shù)據(jù)無關(guān)的東西在流打開的時(shí)候都被跳過了。
public final InputStream openStream() throws IOException
使用reader或者InputStream來獲取數(shù)據(jù):
try {
URL u = new URL("http://www.amnesty.org/");
InputStream in = u.openStream();
int b;
while ((b = in.read()) != -1) {
System.out.write(b);
}
}
catch (MalformedURLException e) {System.err.println(e);}
catch (IOException e) {System.err.println(e);}