OkHttp使用

OkHttp3.0下载文件

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) {
                    }
                }
            }
        });
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值