OkHttp3.0下载文件

作者: 寒江楓雨 | 来源:发表于2019-07-03 16:07 被阅读2次

1 首先要在app/build.gradle中添加依赖,另外注意清单文件中打开相应网络访问权限如:

    implementation 'com.squareup.okhttp3:okhttp:3.14.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.14.1'
    implementation 'com.squareup.okio:okio:1.6.0'

2 创建一个OkHttpclient

         OkHttpClient okHttpClient = new OkHttpClient();

3 创建Request

    Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")    //这里不设置可能产生EOF错误
                .build();

4 获取下载进度

                    InputStream is = null;
                    byte[] buf = new byte[2048];
                   int len = 0;
                   FileOutputStream fos = null;
                   is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        LogUtil.e(TAG,"download progress : " + progress);
                        mView.onDownloading("",progress);
                    }
                    fos.flush();

5 附完整代码

public void downloadFile() {
        final String url = "http://127.0.0.1:8080/park/map/download/test.mp3";
        final long startTime = System.currentTimeMillis();
        LogUtil.i(TAG,"startTime="+startTime);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                LogUtil.i(TAG,"download failed");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mapdata/download";
                if(!FileUtils.isFolderExists(savePath)){
                    FileUtils.makeDirectory(savePath);
                }
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        LogUtil.e(TAG,"download progress : " + progress);
                        mView.onDownloading("",progress);
                    }
                    fos.flush();
                    LogUtil.e(TAG,"download success");
                    LogUtil.e(TAG,"totalTime="+ (System.currentTimeMillis() - startTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.e(TAG,"download failed : "+e.getMessage());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

相关文章

  • OkHttp3.0下载文件

    1 首先要在app/build.gradle中添加依赖,另外注意清单文件中打开相应网络访问权限如: 2 创建一个...

  • Android网络框架

    Android OKHttp3.0 以上使用方法 Android OKHttp3.0 以上使用方法详解Retrof...

  • Android okhttp3.0 框架使用总结

    最近工作主要用到OkHttp3.0网络请求框架,进行Get请求,Post请求,多文件上传等功能,本文内容大部分来源...

  • Android 零碎知识点和技巧

    使用DownloadManager下载文件 下载文件 监听下载结果 文件下载断点续传 1.获取已下载的文件长度. ...

  • js文件下载

    1.文件流下载 根据后台接口文件流下载 调用 2.文件地址下载 根据文件地址下载文件 调用 3.base64流下载...

  • wget下载数据

    下载单个文件 -nc: 继续下载中断的操作 下载目录下面所有文件 下载多个文件:

  • Okhttp3.0

    原文:https://blog.csdn.net/m0_38143863/article/details/8022...

  • 文件下载

    由于不同的浏览器兼容不同,对于直接a标签下载文件,有的浏览器可以,有的浏览器会直接播放。为了保证下载操作的正确执行...

  • 文件下载

    常见的文件格式: 文件下载HTML 图片文件下载PHP

  • 文件下载

    IOUtils 的对应包 需要关闭流的对象放在try()内不用写关闭代码

网友评论

    本文标题:OkHttp3.0下载文件

    本文链接:https://www.haomeiwen.com/subject/ofqchctx.html