網路程式設計(七)URL下載網路資源
阿新 • • 發佈:2022-02-16
網路程式設計(七)URL下載網路資源
目錄URL
URL組成
-
統一資源定位符:定位資源,定位網際網路上的某一個資源
-
DNS域名解析:把一個域名(www.baidu.com)變成一個IP
/* url的組成: 協議://ip地址:埠/專案名/資源 */
URL方法
Modifier and Type | Method and Description |
---|---|
boolean |
equals(Object obj) 將此URL與其他物件進行比較。 |
String |
getAuthority() 獲取此的授權部分 URL |
Object |
getContent() 獲取此URL的內容。 |
Object |
getContent(類[] classes) 獲取此URL的內容。 |
int |
getDefaultPort() 獲取與此 URL 的協議的預設埠號。 |
String |
getFile() 獲取此 URL 的檔名。 |
String |
getHost() 獲取此 URL 的主機名(如適用)。 |
String |
getPath() 獲取此 URL 的路徑部分。 |
int |
getPort() 獲取此 URL 的埠號。 |
String |
getProtocol() 獲取此 URL 的協議名稱。 |
String |
getQuery() 獲取此 URL 的查詢部分。引數 |
String |
getRef() 獲取此的錨定(也稱為“參考”) URL 。 |
String |
getUserInfo() 獲取該 URL 的userInfo部分。 |
int |
hashCode() 建立適合雜湊表索引的整數。 |
URLConnection |
openConnection() 返回一個URLConnection 例項,表示與URL引用的遠端物件的URL 。 |
URLConnection |
openConnection(Proxy proxy) 與openConnection() 相同,但連線將通過指定的代理進行; 不支援代理的協議處理程式將忽略代理引數並進行正常連線。 |
InputStream |
openStream() 開啟與此 URL ,並返回一個 InputStream ,以便從該連線讀取。 |
boolean |
sameFile(URL other) 比較兩個URL,不包括片段元件。 |
static void |
setURLStreamHandlerFactory(URLStreamHandlerFactory fac) 設定應用程式的 URLStreamHandlerFactory 。 |
String |
toExternalForm() 構造這個 URL 的字串 URL 。 |
String |
toString() 構造此 URL 的字串表示 URL 。 |
URI |
toURI() 返回相當於此URL的URI 。 |
常用方法
String |
getFile() 獲取此 URL 的檔名。 |
---|---|
String |
getHost() 獲取此 URL 的主機名(如適用)。 |
String |
getPath() 獲取此 URL 的路徑部分。 |
int |
getPort() 獲取此 URL 的埠號。 |
String |
getProtocol() 獲取此 URL 的協議名稱。 |
String |
getQuery() 獲取此 URL 的查詢部分,引數。 |
URL下載程式碼例項
public class URLDemo01 {
public static void main(String[] args) throws Exception{
//1.下載地址
URL url = new URL("http://localhost:8080/sxp/123ad.txt");
//2.連線到這個資源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream =urlConnection.getInputStream();
FileOutputStream fos=new FileOutputStream("123ad.txt");
byte[] buffer=new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
inputStream.close();
urlConnection.disconnect();//斷開連線
}
}