在上一个例子中,我们展示了使用 HttpURLConnection 进行文件下载的简单实现。在更复杂的应用中,通常会使用一些现代的网络库,例如 OkHttp,以提供更强大、灵活和高性能的文件下载功能。以下是使用 OkHttp 进行文件下载的示例:

1. 添加OkHttp库依赖:

在 build.gradle 文件中添加 OkHttp 的依赖:
implementation 'com.squareup.okhttp3:okhttp:4.9.1'

请确保使用最新版本的 OkHttp。

2. 实现文件下载的 AsyncTask 使用 OkHttp:
import android.os.AsyncTask;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.FileOutputStream;
import java.io.InputStream;

public class FileDownloadTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        String fileUrl = params[0];
        String destinationPath = params[1];

        try {
            return downloadFile(fileUrl, destinationPath);
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    private String downloadFile(String fileUrl, String destinationPath) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(fileUrl).build();
        Response response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            throw new RuntimeException("Failed to download file: " + response);
        }

        ResponseBody body = response.body();
        if (body == null) {
            throw new RuntimeException("Empty response body");
        }

        // 获取文件长度
        long fileLength = body.contentLength();

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            inputStream = body.byteStream();
            fileOutputStream = new FileOutputStream(destinationPath);

            byte[] buffer = new byte[4096];
            long totalBytesRead = 0;
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                totalBytesRead += bytesRead;
                fileOutputStream.write(buffer, 0, bytesRead);

                // 可以在这里更新下载进度
                // publishProgress((int) ((totalBytesRead * 100) / fileLength));
            }

            return "File downloaded successfully";

        } finally {
            // 关闭流
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
    }

    @Override
    protected void onPostExecute(String result) {
        // 处理下载结果
        // result 包含文件下载成功或失败的消息
    }
}

3. 使用 AsyncTask 进行文件下载:
String fileUrl = "URL of the file to download";
String destinationPath = "Local path to save the downloaded file";

FileDownloadTask fileDownloadTask = new FileDownloadTask();
fileDownloadTask.execute(fileUrl, destinationPath);

在这个例子中,使用 OkHttp 来执行文件下载,相较于 HttpURLConnection,OkHttp 提供了更简单、灵活和高效的 API。另外,OkHttp 还支持断点续传、进度监听等更高级的功能。使用 OkHttp 可以使代码更为简洁,并提高网络请求的性能。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15198/Android