- 通過在 URL 上調用
方法建立連接配接對象。(HttpURLConnection conn = (HttpURLConnection)new URL("網址").openConnection();)openConnection
- 處理設定參數和一般請求屬性。(conn.
)setRequestProperty()
- 使用
方法建立到遠端對象的實際連接配接。(conn.connect())connect
- 遠端對象變為可用。遠端對象的頭字段和内容變為可通路。(conn.
)getHeaderField(),conn.
getInputStream等方法對連接配接進行操作
下面是對檔案下載下傳的具體實作案例(單線程):
HttpURLConnection conn = (HttpURLConnection)new URL("資源網址").openConnection();
conn.connect();
InputStream is = connection.getInputStream();
FileOutputStream os = new FileOutputStream("儲存路徑");
int count = 1024;
if(connection.getResponseCode()==200){
while ((count = is.read(b))!=-1) {
os.write(b,0,count);
}
os.close();
is.close();
}
多線程要設定的頭檔案:connection.setRequestProperty("Range", "bytes=0-4194304");
轉載于:https://www.cnblogs.com/wbjgogogo/p/4949803.html