SoFunction
Updated on 2025-03-09

Android file download instance code based on HttpUrlConnection class

I won’t say much nonsense, I will just post the code to you. The specific code is as shown:

/**
    * File download of get method
    * <p>
    * Special note: ProgressBar in Android is the only control that Google has processed to update the UI in child threads
    *
    * @param path
    */
  private void httpDown(final String path) {
    new Thread() {
      @Override
      public void run() {
        URL url;
        HttpURLConnection connection;
        try {
          //Unified resources          url = new URL(path);
          //Open the link          connection = (HttpURLConnection) ();
          //Set the link timeout          (4000);
          //Setting allows the server input stream, the default is true and you don't need to set it          (true);
          //Setting allows writing data to the server. Generally, get methods are not set. Most of them are used in the post method, and the default is false          (true);//This is just for the explanation of the method          //Set request method          ("GET");
          //Set the requested character encoding          ("Charset", "utf-8");
          //Set connection to open link resources          ();
          //Get the file path in the link address          String urlFilePath = ().getFile();
          //Get the total file name of the url address. The separatorChar parameter of the file represents the file separator character          String fileName = (() + 1);
          //Create a file object to store downloaded files. This getFilesDir() method is only in the class inherited to the Context class.          // You can directly call other classes that must be called through Context objects, and what you get is the file path under the application package name in the internal storage          //If you use external storage, you need to add file read and write permissions. Systems above 5.0 need to obtain permissions dynamically. I won’t explain too much here.          File file = new File(getFilesDir(), fileName);
          //Create a file output stream          FileOutputStream outputStream = new FileOutputStream(file);
          //Get the response code of the link 200 is successful          int responseCode = ();
          if (responseCode == HttpURLConnection.HTTP_OK) {
            //Get the input stream of the server response            InputStream inputStream = ();
            //Get the total length of the requested content            int contentLength = ();
            //Set the Max of progressBar            (contentLength);
            //Creating buffered input stream objects is more efficient than inputStream            BufferedInputStream bfi = new BufferedInputStream(inputStream);
            //The len here indicates the length of content read per loop            int len;
            //Total length has been read            int totle = 0;
            //bytes is used to store the content read every time            byte[] bytes = new byte[1024];
            while ((len = (bytes)) != -1) {
              //Every time I read it, the len will be accumulated in the totle              totle += len;
              //Every time the read progressBar is updated              (totle);
              //Write data read from the server through file output stream              (bytes, 0, len);
            }
            //Close open stream object            ();
            ();
            ();
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                (, "Download is complete!", Toast.LENGTH_SHORT).show();
              }
            });
          }
        } catch (Exception e) {
          ();
        }
      }
    }.start();
  }

Summarize

The above is the Android file download example code based on HttpUrlConnection class introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!