1. 程式人生 > >模擬下載某個檔案

模擬下載某個檔案

@SuppressWarnings("resource")
@Test
public void test() throws Exception{
//表示的是一個URL地址
URL url = new URL("http://192.168.10.150:8080/txt/hello.html");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());

//開啟一個連線
URLConnection openConnection = url.openConnection();
//URLConnection轉成HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) openConnection;
//連線伺服器
conn.connect();

int responseCode = conn.getResponseCode();
//連線伺服器成功
if(responseCode == 200){
//獲取輸入流
InputStream is = conn.getInputStream();
//建立輸出流
FileOutputStream fos = new FileOutputStream("123.txt");
//一邊讀一邊寫
byte[] b = new byte[100];
int len = 0;
while((len  = is.read(b)) != -1){
fos.write(b, 0, len);
}
//關閉流
fos.close();
is.close();
}
}