OKHttp3学习之六:文件下载(简单方式)

需求:下载网络文件到手机SD卡上

在app模块的build.gradle配置

compile 'com.squareup.okhttp3:okhttp:3.4.2'

实现源码

private static final String fileUrl = "http://dldir1.qq.com/weixin/android/weixin6331android940.apk";
private static final String fileName = "weixin6331android940.apk";

public void downloadFile(View view) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(fileUrl).build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i(TAG, "请求失败: " + e.getLocalizedMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                ResponseBody body = response.body();
                if (body != null) {
                    writeFile(body);
                }
            }
        }
    });
}

//主线程更新UI进度
private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                int progress = msg.arg1;
                mProgressBar.setProgress(progress);
                break;

            default:
                break;
        }
    }
};

private void writeFile(ResponseBody body) {
    InputStream is = null;  //网络输入流
    FileOutputStream fos = null;  //文件输出流

    is = body.byteStream();

    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;
    File file = new File(filePath);
    try {
        fos = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int len = 0;
        long totalSize = body.contentLength();  //文件总大小
        long sum = 0;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
            sum += len;
            int progress = (int) (sum * 1.0f / totalSize * 100);
            Message msg = handler.obtainMessage();
            msg.what = 1;
            msg.arg1 = progress;
            handler.sendMessage(msg);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
上一篇 OKHttp3学习之五:POST请求(JSON参数形式)
下一篇 OKHttp3学习之七:文件下载(拦截器方式)
目录
文章列表
1 Robot Framework 自定义自己的Python库
Robot Framework 自定义自己的Python库
2
Swift UI - 分段选择控件(UISegmentedControl)
Swift UI - 分段选择控件(UISegmentedControl)
3
Android获取APP当前进程的名称
Android获取APP当前进程的名称
4
RocketMQ详解——RocketMQ的消息模式
RocketMQ详解——RocketMQ的消息模式
5
OKHttp锁定证书CertificatePinner
OKHttp锁定证书CertificatePinner
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。