Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

android 連接服務器下載文件工具類

編輯:關於 Android 程式設計

下面是一個通過 HttpURLConnection 連接服務器並下載文件的工具方法,同時借助 ProgressDialog 實時展示下載進度:

public static File downLoad(String serverPath,String savedPath,ProgressDialog dialog){ try { URL url=new URL(serverPath); HttpURLConnection _conn=(HttpURLConnection) url.openConnection(); _conn.setRequestMethod("GET"); _conn.setConnectTimeout(5000); int code=_conn.getResponseCode(); if(code==200){ //設置進度條的長度 dialog.setMax(_conn.getContentLength()); InputStream is=_conn.getInputStream(); File _file=new File(savedPath); FileOutputStream _FileOutputStream=new FileOutputStream(_file); int len=0; byte[] buffer= new byte[1024]; int _total=0; while((len=is.read(buffer))!=-1){ _FileOutputStream.write(buffer, 0,len); _total+=len; dialog.setProgress(_total); Thread.sleep(20); } _FileOutputStream.flush(); _FileOutputStream.close(); is.close(); return _file; }else { return null; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } }

該方法以 GET 方式請求指定服務器路徑,設置 5 秒連接超時,當響應碼為 200 時,根據文件總大小設置進度條上限,再通過 1024 字節的緩衝區循環讀寫,並實時更新已下載進度,最終返回保存好的文件對象。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved