Search in sources :

Example 1 with DownloadFileInfo

use of com.okhttplib.bean.DownloadFileInfo in project OkHttp3 by MrZhousf.

the class DownUpLoadHelper method downloadFile.

/**
     * 文件下载
     */
void downloadFile(final OkHttpHelper helper) {
    try {
        final HttpInfo info = httpInfo;
        final DownloadFileInfo fileInfo = helper.getDownloadFileInfo();
        String url = fileInfo.getUrl();
        if (TextUtils.isEmpty(url)) {
            showLog("下载文件失败:文件下载地址不能为空!");
            return;
        }
        info.setUrl(url);
        ProgressCallback progressCallback = fileInfo.getProgressCallback();
        //获取文件断点
        long completedSize = fetchCompletedSize(fileInfo);
        fileInfo.setCompletedSize(completedSize);
        //添加下载任务
        if (null == downloadTaskMap)
            downloadTaskMap = new ConcurrentHashMap<>();
        if (downloadTaskMap.containsKey(fileInfo.getSaveFileNameEncrypt())) {
            showLog(fileInfo.getSaveFileName() + " 已在下载任务中");
            return;
        }
        downloadTaskMap.put(fileInfo.getSaveFileNameEncrypt(), fileInfo.getSaveFileNameEncrypt());
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), fileInfo, timeStamp, requestTag)).build();
            }
        };
        //采用新的OkHttpClient处理多线程干扰回调进度问题
        OkHttpClient httpClient = helper.getClientBuilder().addInterceptor(interceptor).build();
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url).header("RANGE", "bytes=" + completedSize + "-");
        helper.getHttpHelper().addHeadsToRequest(info, requestBuilder);
        Request request = requestBuilder.build();
        helper.setRequest(request);
        helper.setHttpClient(httpClient);
        helper.getHttpHelper().responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_DOWNLOAD_CALLBACK, requestTag);
        //删除下载任务
        if (null != downloadTaskMap) {
            downloadTaskMap.remove(fileInfo.getSaveFileNameEncrypt());
        }
    } catch (Exception e) {
        showLog("下载文件失败:" + e.getMessage());
    }
}
Also used : DownloadFileInfo(com.okhttplib.bean.DownloadFileInfo) OkHttpClient(okhttp3.OkHttpClient) ProgressCallback(com.okhttplib.callback.ProgressCallback) Request(okhttp3.Request) ProgressResponseBody(com.okhttplib.progress.ProgressResponseBody) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Interceptor(okhttp3.Interceptor)

Example 2 with DownloadFileInfo

use of com.okhttplib.bean.DownloadFileInfo in project OkHttp3 by MrZhousf.

the class DownUpLoadHelper method downloadingFile.

/**
     * 开始文件下载
     */
HttpInfo downloadingFile(OkHttpHelper okHttpInfo, Response res, Call call) {
    final HttpInfo info = httpInfo;
    final DownloadFileInfo fileInfo = okHttpInfo.getDownloadFileInfo();
    RandomAccessFile accessFile = null;
    InputStream inputStream = null;
    BufferedInputStream bis = null;
    String filePath = fileInfo.getSaveFileDir() + fileInfo.getSaveFileNameWithExtension();
    try {
        ResponseBody responseBody = res.body();
        int length;
        long completedSize = fileInfo.getCompletedSize();
        accessFile = new RandomAccessFile(fileInfo.getSaveFileDir() + fileInfo.getSaveFileNameEncrypt(), "rwd");
        //服务器不支持断点下载时重新下载
        if (TextUtils.isEmpty(res.header("Content-Range"))) {
            completedSize = 0L;
            fileInfo.setCompletedSize(completedSize);
        }
        accessFile.seek(completedSize);
        inputStream = responseBody.byteStream();
        byte[] buffer = new byte[2048];
        bis = new BufferedInputStream(inputStream);
        fileInfo.setDownloadStatus(DownloadStatus.DOWNLOADING);
        while ((length = bis.read(buffer)) > 0 && (DownloadStatus.DOWNLOADING.equals(fileInfo.getDownloadStatus()))) {
            accessFile.write(buffer, 0, length);
            completedSize += length;
        }
        if (DownloadStatus.PAUSE.equals(fileInfo.getDownloadStatus())) {
            return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.Message, "暂停下载");
        }
        //下载完成
        if (DownloadStatus.DOWNLOADING.equals(fileInfo.getDownloadStatus())) {
            fileInfo.setDownloadStatus(DownloadStatus.COMPLETED);
            File newFile = new File(fileInfo.getSaveFileDir(), fileInfo.getSaveFileNameWithExtension());
            //处理文件已存在逻辑
            if (newFile.exists() && newFile.isFile()) {
                filePath = fileInfo.getSaveFileDir() + fileInfo.getSaveFileNameCopy();
                newFile = new File(fileInfo.getSaveFileDir(), fileInfo.getSaveFileNameCopy());
            }
            File oldFile = new File(fileInfo.getSaveFileDir(), fileInfo.getSaveFileNameEncrypt());
            if (oldFile.exists() && oldFile.isFile()) {
                boolean rename = oldFile.renameTo(newFile);
                showLog("重命名[" + rename + "]:" + newFile.getAbsolutePath());
            }
            return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.SUCCESS, filePath);
        }
    } catch (SocketTimeoutException e) {
        return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.WriteAndReadTimeOut);
    } catch (SocketException e) {
        return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.ConnectionInterruption, e.getMessage());
    } catch (Exception e) {
        showLog("文件下载异常:" + e.getMessage());
        return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.ConnectionInterruption);
    } finally {
        try {
            if (null != bis)
                bis.close();
            if (null != inputStream)
                inputStream.close();
            if (null != accessFile)
                accessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BaseActivityLifecycleCallbacks.cancel(requestTag, call);
        //删除下载任务
        if (null != downloadTaskMap)
            downloadTaskMap.remove(fileInfo.getSaveFileNameEncrypt());
    }
    return okHttpInfo.getHttpHelper().retInfo(info, HttpInfo.SUCCESS, filePath);
}
Also used : SocketException(java.net.SocketException) DownloadFileInfo(com.okhttplib.bean.DownloadFileInfo) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) ProgressResponseBody(com.okhttplib.progress.ProgressResponseBody) HttpInfo(com.okhttplib.HttpInfo) SocketTimeoutException(java.net.SocketTimeoutException) RandomAccessFile(java.io.RandomAccessFile) BufferedInputStream(java.io.BufferedInputStream) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 3 with DownloadFileInfo

use of com.okhttplib.bean.DownloadFileInfo in project OkHttp3 by MrZhousf.

the class DownloadBreakpointsActivity method download.

private void download() {
    if (null == fileInfo)
        fileInfo = new DownloadFileInfo(url, "test", new ProgressCallback() {

            @Override
            public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
                downloadProgress.setProgress(percent);
                tvResult.setText(percent + "%");
                LogUtil.d(TAG, "下载进度:" + percent);
            }

            @Override
            public void onResponseMain(String filePath, HttpInfo info) {
                if (info.isSuccessful()) {
                    tvResult.setText(info.getRetDetail() + "\n下载状态:" + fileInfo.getDownloadStatus());
                } else {
                    Toast.makeText(DownloadBreakpointsActivity.this, info.getRetDetail(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    HttpInfo info = HttpInfo.Builder().addDownloadFile(fileInfo).build();
    OkHttpUtil.Builder().setReadTimeout(120).build(this).doDownloadFileAsync(info);
}
Also used : HttpInfo(com.okhttplib.HttpInfo) DownloadFileInfo(com.okhttplib.bean.DownloadFileInfo) ProgressCallback(com.okhttplib.callback.ProgressCallback)

Aggregations

HttpInfo (com.okhttplib.HttpInfo)3 DownloadFileInfo (com.okhttplib.bean.DownloadFileInfo)3 ProgressCallback (com.okhttplib.callback.ProgressCallback)2 ProgressResponseBody (com.okhttplib.progress.ProgressResponseBody)2 IOException (java.io.IOException)2 SocketException (java.net.SocketException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 InputStream (java.io.InputStream)1 RandomAccessFile (java.io.RandomAccessFile)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Interceptor (okhttp3.Interceptor)1 OkHttpClient (okhttp3.OkHttpClient)1 Request (okhttp3.Request)1 Response (okhttp3.Response)1 ResponseBody (okhttp3.ResponseBody)1