Search in sources :

Example 11 with HttpInfo

use of com.okhttplib.HttpInfo 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 12 with HttpInfo

use of com.okhttplib.HttpInfo 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 13 with HttpInfo

use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.

the class HttpHelper method doRequestSync.

/**
     * 同步请求
     */
HttpInfo doRequestSync(OkHttpHelper helper) {
    Call call = null;
    final HttpInfo info = httpInfo;
    Request request = helper.getRequest();
    String url = info.getUrl();
    if (!checkUrl(url)) {
        return retInfo(info, HttpInfo.CheckURL);
    }
    request = request == null ? buildRequest(info, helper.getRequestMethod(), helper.getProgressCallback()) : request;
    showUrlLog(request);
    helper.setRequest(request);
    OkHttpClient httpClient = helper.getHttpClient();
    try {
        httpClient = httpClient == null ? super.httpClient : httpClient;
        call = httpClient.newCall(request);
        BaseActivityLifecycleCallbacks.putCall(requestTag, call);
        Response res = call.execute();
        return dealResponse(helper, res, call);
    } catch (IllegalArgumentException e) {
        return retInfo(info, HttpInfo.ProtocolException);
    } catch (SocketTimeoutException e) {
        if (null != e.getMessage()) {
            if (e.getMessage().contains("failed to connect to"))
                return retInfo(info, ConnectionTimeOut);
            if (e.getMessage().equals("timeout"))
                return retInfo(info, WriteAndReadTimeOut);
        }
        return retInfo(info, WriteAndReadTimeOut);
    } catch (UnknownHostException e) {
        if (!helperInfo.getOkHttpUtil().isNetworkAvailable()) {
            return retInfo(info, HttpInfo.CheckNet, "[" + e.getMessage() + "]");
        } else {
            return retInfo(info, HttpInfo.CheckURL, "[" + e.getMessage() + "]");
        }
    } catch (NetworkOnMainThreadException e) {
        return retInfo(info, HttpInfo.NetworkOnMainThreadException);
    } catch (Exception e) {
        return retInfo(info, HttpInfo.NoResult, "[" + e.getMessage() + "]");
    } finally {
        BaseActivityLifecycleCallbacks.cancel(requestTag, call);
    }
}
Also used : HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) Request(okhttp3.Request) NetworkOnMainThreadException(android.os.NetworkOnMainThreadException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) NetworkOnMainThreadException(android.os.NetworkOnMainThreadException)

Example 14 with HttpInfo

use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.

the class HttpHelper method dealResponse.

/**
     * 处理HTTP响应
     */
private HttpInfo dealResponse(OkHttpHelper helper, Response res, Call call) {
    showLog(String.format(Locale.getDefault(), "CostTime: %.3fs", (System.nanoTime() - startTime) / 1e9d));
    final HttpInfo info = httpInfo;
    BufferedReader bufferedReader = null;
    String result = "";
    try {
        if (null != res) {
            final int netCode = res.code();
            if (res.isSuccessful()) {
                if (helper.getBusinessType() == BusinessType.HttpOrHttps || helper.getBusinessType() == BusinessType.UploadFile) {
                    //服务器响应编码格式
                    String encoding = info.getResponseEncoding();
                    if (TextUtils.isEmpty(encoding)) {
                        encoding = helper.getResponseEncoding();
                    }
                    bufferedReader = new BufferedReader(new InputStreamReader(res.body().byteStream(), encoding));
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    return retInfo(info, netCode, HttpInfo.SUCCESS, result);
                } else if (helper.getBusinessType() == BusinessType.DownloadFile) {
                    //下载文件
                    return helper.getDownUpLoadHelper().downloadingFile(helper, res, call);
                }
            } else {
                showLog("HttpStatus: " + netCode);
                if (netCode == 400) {
                    return retInfo(info, netCode, HttpInfo.RequestParamError);
                } else if (netCode == 404) {
                    //请求页面路径错误
                    return retInfo(info, netCode, HttpInfo.ServerNotFound);
                } else if (netCode == 416) {
                    //请求数据流范围错误
                    return retInfo(info, netCode, HttpInfo.Message, "请求Http数据流范围错误\n" + result);
                } else if (netCode == 500) {
                    //服务器内部错误
                    return retInfo(info, netCode, HttpInfo.NoResult);
                } else if (netCode == 502) {
                    //错误的网关
                    return retInfo(info, netCode, HttpInfo.GatewayBad);
                } else if (netCode == 504) {
                    //网关超时
                    return retInfo(info, netCode, HttpInfo.GatewayTimeOut);
                } else {
                    return retInfo(info, netCode, HttpInfo.CheckNet);
                }
            }
        }
        return retInfo(info, HttpInfo.CheckURL);
    } catch (Exception e) {
        return retInfo(info, HttpInfo.NoResult, "[" + e.getMessage() + "]");
    } finally {
        if (null != res) {
            res.close();
        }
        if (null != bufferedReader) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : HttpInfo(com.okhttplib.HttpInfo) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) NetworkOnMainThreadException(android.os.NetworkOnMainThreadException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 15 with HttpInfo

use of com.okhttplib.HttpInfo in project OkHttp3 by MrZhousf.

the class DownloadActivity method downloadFile.

private void downloadFile() {
    final HttpInfo info = HttpInfo.Builder().addDownloadFile(fileURL, "myMP4", 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) {
            tvResult.setText(info.getRetDetail());
            LogUtil.d(TAG, "下载结果:" + info.getRetDetail());
        }
    }).build();
    OkHttpUtil.Builder().setReadTimeout(120).build(//绑定请求标识
    requestTag).doDownloadFileAsync(info);
}
Also used : HttpInfo(com.okhttplib.HttpInfo) ProgressCallback(com.okhttplib.callback.ProgressCallback)

Aggregations

HttpInfo (com.okhttplib.HttpInfo)21 IOException (java.io.IOException)12 ProgressCallback (com.okhttplib.callback.ProgressCallback)10 Callback (com.okhttplib.callback.Callback)6 SocketTimeoutException (java.net.SocketTimeoutException)6 Request (okhttp3.Request)4 DownloadFileInfo (com.okhttplib.bean.DownloadFileInfo)3 SocketException (java.net.SocketException)3 UnknownHostException (java.net.UnknownHostException)3 Call (okhttp3.Call)3 Response (okhttp3.Response)3 NetworkOnMainThreadException (android.os.NetworkOnMainThreadException)2 CallbackMessage (com.okhttplib.bean.CallbackMessage)2 DownloadMessage (com.okhttplib.bean.DownloadMessage)2 UploadMessage (com.okhttplib.bean.UploadMessage)2 BaseCallback (com.okhttplib.callback.BaseCallback)2 ProgressResponseBody (com.okhttplib.progress.ProgressResponseBody)2 File (java.io.File)2 RandomAccessFile (java.io.RandomAccessFile)2 OkHttpClient (okhttp3.OkHttpClient)2