在 Android 中进行文件下载通常涉及到与服务器的交互,并且涉及到使用 HTTP 协议的 GET 请求。下面是一个简单的 Android 文件下载的示例,使用 HttpURLConnection 进行文件下载。

1. 添加网络权限:

在 AndroidManifest.xml 文件中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />

2. 实现文件下载的 AsyncTask:
import android.os.AsyncTask;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloadTask extends AsyncTask<String, Void, 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 {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置连接属性
            connection.setDoInput(true);
            connection.connect();

            // 获取文件长度
            int fileLength = connection.getContentLength();

            // 输入流
            inputStream = connection.getInputStream();

            // 输出流
            fileOutputStream = new FileOutputStream(destinationPath);

            // 缓冲区
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalBytesRead = 0;

            // 下载文件
            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);

请确保将 "URL of the file to download" 替换为实际的文件下载 URL,将 "Local path to save the downloaded file" 替换为实际文件保存的本地路径。

在这个例子中,使用 HttpURLConnection 来执行文件下载,通过设置请求头和从输入流中读取数据的方式完成文件下载。在实际应用中,你可能需要根据服务器端的要求调整请求头和请求体的格式。另外,为了避免在主线程执行网络操作,你可能需要在 doInBackground 方法中使用 runOnUiThread 或者使用 AsyncTask 的 onProgressUpdate 方法来更新 UI。


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