溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android應用中的斷點下載功能怎么利用HttpURLConnection實現

發布時間:2020-12-05 16:32:04 來源:億速云 閱讀:209 作者:Leah 欄目:移動開發

Android應用中的斷點下載功能怎么利用HttpURLConnection實現?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

HttpCilent 跟 HttpURLConnection 是安卓原生的用來實現http請求的類:
Android 6.0之后取消了HttpClient,不支持跟新 ,今天小編使用的是HttpURLConnection :

直接上代碼:

 URL url = null;
      BufferedInputStream bin = null;
      HttpURLConnection httpURLConnection = null;
      Context context;
      try {
      //你要下載文件的路徑
        String urlPath = "MyUrlPath"

        long fileSize = file.length;

        //獲取開始下載位置
        long startOffset = getFileLength(context);
        url = new URL(urlPath);
        //獲取HttpURLConnection對象
        httpURLConnection = (HttpURLConnection) url.openConnection();
        //設置請求方式
        httpURLConnection.setRequestMethod("GET");
        //設置字符編碼,這個字符編碼表示為頭500個字節:Range: bytes=0-499
          表示第二個500字節:Range: bytes=500-999
          表示最后500個字節:Range: bytes=-500
          表示500字節以后的范圍:Range: bytes=500-
          第一個和最后一個字節:Range: bytes=0-0,-1
          同時指定幾個范圍:Range: bytes=500-600,601-999
        httpURLConnection.setRequestProperty("Range" , "bytes=" + startOffset + "-");
        // 打開到此 URL 引用的資源的通信鏈接(如果尚未建立這樣的連接)。
        httpURLConnection.connect();
        if(httpURLConnection.getResponseCode() == 206){
         //if startOffset ==0 的時候,你就要把你的文件大小保存起來
          //獲取文件的大小httpURLConnection.getContentLength();
          //當你第一次下載的時候,也就是你的起始位置是0的時候,這就是這個文件的總大小,如果bytes=xx 的范圍大于0,那么你獲取的值就是你的文件總大小-bytes
          //獲取文件輸出流
          bin = new BufferedInputStream(httpURLConnection.getInputStream());
          //這個是你要保存在那個目錄的位置
          File folder= new File(DOWNLOADDIR);
          //如果文件夾不存在則新建一個文件夾
          if(!folder.exists()){
            folder.mkdirs();
          }

          // 隨機訪問文件,可以指定斷點續傳的起始位置
          //flieAbsolutePath 是你具體的文件路徑
          RandomAccessFile randomAccessFile = new RandomAccessFile(flieAbsolutePath , "rwd");
// rwd 跟 r 跟 w的區別是rwd:邊讀編寫邊下載 r讀 w寫          
          randomAccessFile.seek(startOffset);
          byte[] buffer = new byte[2048];
          int len;
          //isStop可以用來實現暫停功能
          while ((len = bin.read(buffer)) != -1 && !isStop) {
            randomAccessFile.write(buffer, 0, len);
            startOffset += len;
            //刷新下載進度
            Message msg = new Message();
            msg.what = (int)((startOffset * 100) / fileSize);
            //使用handler發送消息刷新UI
            handler.sendMessage(msg);
            //保存下載的位置到SharedPreferences,下次下載的時候拿值寫入設置字符編碼
            saveFileLength(context , startOffset);
          }
        }
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }finally {
        if(url != null){
          url = null;

        }
        if(bin != null){
          try {
            bin.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if(httpURLConnection != null){
          httpURLConnection.disconnect();
        }

      }
      return null;
    }

/**
   * 保存文件長度
   * @param context
   * @param fileLength
   */
  private static void saveFileLength(Context context ,Long fileLength ){
    SharedPreferences sp = context.getSharedPreferences("My_SP" , Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putLong("File_startOffset" , fileLength);
    editor.commit();
  }
/**
   * 獲取文件長度
   * @param context
   * @return
   */
  private static Long getFileLength(Context context){
    SharedPreferences sp = context.getSharedPreferences("My_SP" , Context.MODE_PRIVATE);
    return sp.getLong("File_startOffset" , 0);
  }

看完上述內容,你們掌握Android應用中的斷點下載功能怎么利用HttpURLConnection實現的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女