SoFunction
Updated on 2025-03-11

Android HttpURLConnection breakpoint download (single threaded)

HttpCilent and HttpURLConnection are Android native classes used to implement http requests:
After Android 6.0, HttpClient was cancelled and does not support new content. Today, the editor uses HttpURLConnection:

Directly upload the code:

 URL url = null;
      BufferedInputStream bin = null;
      HttpURLConnection httpURLConnection = null;
      Context context;
      try {
      //The path to download the file        String urlPath = "MyUrlPath"

        long fileSize = ;

        //Get the start download location        long startOffset = getFileLength(context);
        url = new URL(urlPath);
        //Get the HttpURLConnection object        httpURLConnection = (HttpURLConnection) ();
        //Set request method        ("GET");
        //Set character encoding, this character encoding is expressed as the header 500 bytes: Range: bytes=0-499          Indicates the second500byte:Range: bytes=500-999
          Indicates the last500个byte:Range: bytes=-500
          express500byte以后的范围:Range: bytes=500-
          第一个和最后一个byte:Range: bytes=0-0,-1
          Specify several ranges at the same time:Range: bytes=500-600,601-999
        ("Range" , "bytes=" + startOffset + "-");
        // Open a communication link to the resource referenced by this URL (if such a connection has not been established).        ();
        if(() == 206){
         //When startOffset ==0, you have to save your file size          //Get the file size ();          //When you download the first time, that is, your starting position is 0, this is the total size of the file. If the range of bytes=xx is greater than 0, then the value you get is the total size of your file - bytes          //Get file output stream          bin = new BufferedInputStream(());
          //This is where you want to save it in that directory          File folder= new File(DOWNLOADDIR);
          //If the folder does not exist, create a new folder          if(!()){
            ();
          }

          // Random access to the file, you can specify the starting position of the breakpoint continuous transmission          //flieAbsolutePath is your specific file path          RandomAccessFile randomAccessFile = new RandomAccessFile(flieAbsolutePath , "rwd");
// The difference between rwd and r and w is rwd: while reading and writing, downloading r read w write          (startOffset);
          byte[] buffer = new byte[2048];
          int len;
          //isStop can be used to implement pause function          while ((len = (buffer)) != -1 && !isStop) {
            (buffer, 0, len);
            startOffset += len;
            //Refresh the download progress            Message msg = new Message();
             = (int)((startOffset * 100) / fileSize);
            //Use handler to send messages to refresh the UI            (msg);
            //Save the download location to SharedPreferences, and write the value to set the character encoding when downloading next time.            saveFileLength(context , startOffset);
          }
        }
      } catch (MalformedURLException e) {
        ();
      } catch (IOException e) {
        ();
      }finally {
        if(url != null){
          url = null;

        }
        if(bin != null){
          try {
            ();
          } catch (IOException e) {
            ();
          }
        }
        if(httpURLConnection != null){
          ();
        }

      }
      return null;
    }

/**
    * Save file length
    * @param context
    * @param fileLength
    */
  private static void saveFileLength(Context context ,Long fileLength ){
    SharedPreferences sp = ("My_SP" , Context.MODE_PRIVATE);
     editor = ();
    ("File_startOffset" , fileLength);
    ();
  }
/**
    * Get file length
    * @param context
    * @return
    */
  private static Long getFileLength(Context context){
    SharedPreferences sp = ("My_SP" , Context.MODE_PRIVATE);
    return ("File_startOffset" , 0);
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.