OkHttp3.0下載文件

1 首先要在app/build.gradle中添加依賴,另外注意清單文件中打開(kāi)相應(yīng)網(wǎng)絡(luò)訪問(wèn)權(quán)限如:

    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 創(chuàng)建一個(gè)OkHttpclient

         OkHttpClient okHttpClient = new OkHttpClient();

3 創(chuàng)建Request

    Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")    //這里不設(shè)置可能產(chǎn)生EOF錯(cuò)誤
                .build();

4 獲取下載進(jìn)度

                    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;
                // 儲(chǔ)存下載文件的目錄
                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) {
                    }
                }
            }
        });
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容