Search in sources :

Example 1 with ProgressCallback

use of com.okhttplib.callback.ProgressCallback 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 ProgressCallback

use of com.okhttplib.callback.ProgressCallback in project OkHttp3 by MrZhousf.

the class UploadImageActivity method uploadImgOne.

/**
     * 上传第一张图片
     */
private void uploadImgOne() {
    HttpInfo info = HttpInfo.Builder().setUrl(url).addUploadFile("uploadFile", filePathOne, new ProgressCallback() {

        //onProgressMain为UI线程回调,可以直接操作UI
        @Override
        public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
            uploadProgressOne.setProgress(percent);
            LogUtil.d(TAG, "上传进度1:" + percent);
        }
    }).build();
    doUploadImg(info);
}
Also used : HttpInfo(com.okhttplib.HttpInfo) ProgressCallback(com.okhttplib.callback.ProgressCallback)

Example 3 with ProgressCallback

use of com.okhttplib.callback.ProgressCallback in project OkHttp3 by MrZhousf.

the class UploadImageActivity method uploadImgMulti.

/**
     * 批量上传:一次性批量上传请使用UploadFileActivity中的doUploadBatch方法
     */
private void uploadImgMulti() {
    HttpInfo info = HttpInfo.Builder().setUrl(url).addUploadFile("file", filePathOne, new ProgressCallback() {

        @Override
        public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
            uploadProgressOne.setProgress(percent);
            LogUtil.d(TAG, "上传进度1:" + percent);
        }

        @Override
        public void onResponseMain(String filePath, HttpInfo info) {
            LogUtil.d(TAG, "上传结果1:\n" + filePath + "\n" + info.getRetDetail());
        }
    }).addUploadFile("file", filePathTwo, new ProgressCallback() {

        @Override
        public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
            uploadProgressTwo.setProgress(percent);
            LogUtil.d(TAG, "上传进度2:" + percent);
        }

        @Override
        public void onResponseMain(String filePath, HttpInfo info) {
            LogUtil.d(TAG, "上传结果2:\n" + filePath + "\n" + info.getRetDetail());
        }
    }).build();
    doUploadImg(info);
}
Also used : HttpInfo(com.okhttplib.HttpInfo) ProgressCallback(com.okhttplib.callback.ProgressCallback)

Example 4 with ProgressCallback

use of com.okhttplib.callback.ProgressCallback in project OkHttp3 by MrZhousf.

the class DownUpLoadHelper method uploadFile.

/**
     * 文件上传
     */
void uploadFile(OkHttpHelper helper) {
    try {
        final HttpInfo info = httpInfo;
        List<UploadFileInfo> uploadFileList = helper.getUploadFileInfoList();
        String url = info.getUrl();
        if (TextUtils.isEmpty(url)) {
            showLog("文件上传接口地址不能为空");
            return;
        }
        StringBuilder log = new StringBuilder("PostParams: ");
        MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        ProgressCallback progressCallback = helper.getProgressCallback();
        String logInfo;
        if (null != info.getParams() && !info.getParams().isEmpty()) {
            for (String key : info.getParams().keySet()) {
                mBuilder.addFormDataPart(key, info.getParams().get(key));
                logInfo = key + " =" + info.getParams().get(key) + ", ";
                log.append(logInfo);
            }
        }
        for (UploadFileInfo fileInfo : uploadFileList) {
            if (progressCallback == null) {
                progressCallback = fileInfo.getProgressCallback();
            }
            String filePath = fileInfo.getFilePathWithName();
            String interfaceParamName = fileInfo.getInterfaceParamName();
            File file = new File(filePath);
            log.append(interfaceParamName);
            log.append("=");
            log.append(filePath);
            log.append(",");
            mBuilder.addFormDataPart(interfaceParamName, file.getName(), RequestBody.create(MediaTypeUtil.fetchFileMediaType(filePath), file));
        }
        showLog(log.toString());
        RequestBody requestBody = mBuilder.build();
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url).post(new ProgressRequestBody(requestBody, progressCallback, timeStamp, requestTag));
        helper.getHttpHelper().addHeadsToRequest(info, requestBuilder);
        Request request = requestBuilder.build();
        helper.setRequest(request);
        helper.getHttpHelper().responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_UPLOAD_CALLBACK, requestTag);
    } catch (Exception e) {
        showLog("上传文件失败:" + e.getMessage());
    }
}
Also used : ProgressCallback(com.okhttplib.callback.ProgressCallback) Request(okhttp3.Request) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) UploadFileInfo(com.okhttplib.bean.UploadFileInfo) MultipartBody(okhttp3.MultipartBody) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ProgressRequestBody(com.okhttplib.progress.ProgressRequestBody) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.okhttplib.progress.ProgressRequestBody)

Example 5 with ProgressCallback

use of com.okhttplib.callback.ProgressCallback in project OkHttp3 by MrZhousf.

the class ProgressResponseBody method source.

private Source source(Source source) {
    return new ForwardingSource(source) {

        long totalBytesRead = 0L;

        long contentLength = 0L;

        ProgressCallback progressCallback;

        int lastPercent = 0;

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead = super.read(sink, byteCount);
            if (totalBytesRead == 0) {
                totalBytesRead = downloadFileInfo.getCompletedSize();
                Log.d(requestTag + "[" + timeStamp + "]", "从节点[" + totalBytesRead + "]开始下载" + downloadFileInfo.getSaveFileNameWithExtension());
            }
            if (contentLength == 0) {
                //文件总长度=当前需要下载长度+已完成长度
                contentLength = contentLength() + totalBytesRead;
            }
            totalBytesRead += bytesRead != -1 ? bytesRead : 0;
            if (null == progressCallback)
                progressCallback = downloadFileInfo.getProgressCallback();
            if (null != progressCallback) {
                int percent = (int) ((100 * totalBytesRead) / contentLength);
                //每处理1%则立即回调
                if (percent != lastPercent) {
                    lastPercent = percent;
                    progressCallback.onProgressAsync(percent, totalBytesRead, contentLength, totalBytesRead == -1);
                    //主线程回调
                    Message msg = new ProgressMessage(OkMainHandler.PROGRESS_CALLBACK, progressCallback, percent, totalBytesRead, contentLength, bytesRead == -1, requestTag).build();
                    OkMainHandler.getInstance().sendMessage(msg);
                }
            }
            return bytesRead;
        }
    };
}
Also used : Buffer(okio.Buffer) ProgressMessage(com.okhttplib.bean.ProgressMessage) Message(android.os.Message) ProgressMessage(com.okhttplib.bean.ProgressMessage) ProgressCallback(com.okhttplib.callback.ProgressCallback) ForwardingSource(okio.ForwardingSource)

Aggregations

ProgressCallback (com.okhttplib.callback.ProgressCallback)10 HttpInfo (com.okhttplib.HttpInfo)9 DownloadFileInfo (com.okhttplib.bean.DownloadFileInfo)2 IOException (java.io.IOException)2 SocketException (java.net.SocketException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 Request (okhttp3.Request)2 Message (android.os.Message)1 ProgressMessage (com.okhttplib.bean.ProgressMessage)1 UploadFileInfo (com.okhttplib.bean.UploadFileInfo)1 ProgressRequestBody (com.okhttplib.progress.ProgressRequestBody)1 ProgressResponseBody (com.okhttplib.progress.ProgressResponseBody)1 File (java.io.File)1 RandomAccessFile (java.io.RandomAccessFile)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Interceptor (okhttp3.Interceptor)1 MultipartBody (okhttp3.MultipartBody)1 OkHttpClient (okhttp3.OkHttpClient)1 RequestBody (okhttp3.RequestBody)1 Response (okhttp3.Response)1