Search in sources :

Example 1 with HttpInfo

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

the class OkMainHandler method handleMessage.

@Override
public void handleMessage(Message msg) {
    final int what = msg.what;
    String requestTag = "";
    try {
        switch(what) {
            case // 网络请求
            RESPONSE_CALLBACK:
                CallbackMessage callMsg = (CallbackMessage) msg.obj;
                if (null != callMsg.callback) {
                    // 开始回调
                    requestTag = callMsg.requestTag;
                    if (!BaseActivityLifecycleCallbacks.isActivityDestroyed(callMsg.requestTag)) {
                        BaseCallback callback = callMsg.callback;
                        if (callback instanceof CallbackOk) {
                            ((CallbackOk) callback).onResponse(callMsg.info);
                        } else if (callback instanceof com.okhttplib.callback.Callback) {
                            HttpInfo info = callMsg.info;
                            if (info.isSuccessful()) {
                                ((com.okhttplib.callback.Callback) callback).onSuccess(info);
                            } else {
                                ((com.okhttplib.callback.Callback) callback).onFailure(info);
                            }
                            // 当返回结果是Response时自动关闭ResponseBody
                            if (info.isNeedResponse()) {
                                Response res = info.getResponse();
                                if (null != res) {
                                    res.close();
                                }
                            }
                        }
                    }
                }
                Call call = callMsg.call;
                if (call != null) {
                    if (!call.isCanceled()) {
                        call.cancel();
                    }
                    BaseActivityLifecycleCallbacks.cancel(requestTag, call);
                }
                break;
            case // 进度回调
            PROGRESS_CALLBACK:
                ProgressMessage proMsg = (ProgressMessage) msg.obj;
                if (null != proMsg.progressCallback) {
                    requestTag = proMsg.requestTag;
                    if (!BaseActivityLifecycleCallbacks.isActivityDestroyed(proMsg.requestTag)) {
                        proMsg.progressCallback.onProgressMain(proMsg.percent, proMsg.bytesWritten, proMsg.contentLength, proMsg.done);
                    }
                }
                break;
            case // 上传结果回调
            RESPONSE_UPLOAD_CALLBACK:
                UploadMessage uploadMsg = (UploadMessage) msg.obj;
                if (null != uploadMsg.progressCallback) {
                    requestTag = uploadMsg.requestTag;
                    if (!BaseActivityLifecycleCallbacks.isActivityDestroyed(requestTag)) {
                        uploadMsg.progressCallback.onResponseMain(uploadMsg.filePath, uploadMsg.info);
                        BaseActivityLifecycleCallbacks.cancel(requestTag);
                    }
                }
                break;
            case // 下载结果回调
            RESPONSE_DOWNLOAD_CALLBACK:
                DownloadMessage downloadMsg = (DownloadMessage) msg.obj;
                if (null != downloadMsg) {
                    requestTag = downloadMsg.requestTag;
                    if (!BaseActivityLifecycleCallbacks.isActivityDestroyed(requestTag)) {
                        downloadMsg.progressCallback.onResponseMain(downloadMsg.filePath, downloadMsg.info);
                        BaseActivityLifecycleCallbacks.cancel(requestTag);
                    }
                }
                break;
            default:
                super.handleMessage(msg);
                break;
        }
    } catch (Exception e) {
        BaseActivityLifecycleCallbacks.cancel(requestTag);
    }
}
Also used : Call(okhttp3.Call) ProgressMessage(com.okhttplib.bean.ProgressMessage) CallbackMessage(com.okhttplib.bean.CallbackMessage) CallbackOk(com.okhttplib.callback.CallbackOk) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) UploadMessage(com.okhttplib.bean.UploadMessage) DownloadMessage(com.okhttplib.bean.DownloadMessage) BaseCallback(com.okhttplib.callback.BaseCallback)

Example 2 with HttpInfo

use of com.okhttplib.HttpInfo 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();
            }
        };
        try {
            // 采用新的OkHttpClient处理多线程干扰回调进度问题
            OkHttpClient httpClient = super.clientBuilder.addInterceptor(interceptor).build();
            Request.Builder requestBuilder = new Request.Builder();
            requestBuilder.url(url).header("RANGE", "bytes=" + completedSize + "-");
            addHeadsToRequest(info, requestBuilder);
            Request request = requestBuilder.build();
            helper.setRequest(request);
            helper.setHttpClient(httpClient);
            responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_DOWNLOAD_CALLBACK, requestTag);
        } finally {
            // 删除下载任务
            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 3 with HttpInfo

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

the class HttpHelper method doRequestAsync.

/**
 * 异步请求
 */
void doRequestAsync(final OkHttpHelper helper) {
    if (httpInfo == null)
        return;
    final HttpInfo info = httpInfo;
    final BaseCallback callback = helper.getCallback();
    Request request = helper.getRequest();
    String url = info.getUrl();
    if (!checkUrl(url)) {
        // 主线程回调
        Message msg = new CallbackMessage(OkMainHandler.RESPONSE_CALLBACK, callback, retInfo(info, HttpInfo.CheckURL), requestTag, null).build();
        OkMainHandler.getInstance().sendMessage(msg);
        return;
    }
    request = request == null ? buildRequest(info, helper.getRequestType(), helper.getProgressCallback()) : request;
    showUrlLog(request);
    Call call = httpClient.newCall(request);
    BaseActivityLifecycleCallbacks.putCall(requestTag, call);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            // 主线程回调
            int code = HttpInfo.CheckNet;
            if (e instanceof UnknownHostException) {
                if (!helperInfo.getOkHttpUtil().isNetworkAvailable()) {
                    code = HttpInfo.CheckNet;
                } else {
                    code = HttpInfo.CheckURL;
                }
            } else if (e instanceof SocketTimeoutException) {
                code = HttpInfo.ConnectionTimeOut;
                if (null != e.getMessage()) {
                    if (e.getMessage().contains("failed to connect to"))
                        code = HttpInfo.ConnectionTimeOut;
                    if (e.getMessage().equals("timeout"))
                        code = HttpInfo.WriteAndReadTimeOut;
                }
            }
            Message msg = new CallbackMessage(OkMainHandler.RESPONSE_CALLBACK, callback, retInfo(info, code, "[" + e.getMessage() + "]"), requestTag, call).build();
            OkMainHandler.getInstance().sendMessage(msg);
        }

        @Override
        public void onResponse(Call call, Response res) throws IOException {
            // 主线程回调
            Message msg = new CallbackMessage(OkMainHandler.RESPONSE_CALLBACK, callback, dealResponse(helper, res), requestTag, call).build();
            OkMainHandler.getInstance().sendMessage(msg);
        }
    });
}
Also used : Call(okhttp3.Call) CallbackMessage(com.okhttplib.bean.CallbackMessage) Message(android.os.Message) UnknownHostException(java.net.UnknownHostException) CallbackMessage(com.okhttplib.bean.CallbackMessage) Request(okhttp3.Request) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) ProgressCallback(com.okhttplib.callback.ProgressCallback) Callback(okhttp3.Callback) BaseCallback(com.okhttplib.callback.BaseCallback) SocketTimeoutException(java.net.SocketTimeoutException) BaseCallback(com.okhttplib.callback.BaseCallback)

Example 4 with HttpInfo

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

the class MainActivity method networkThenCache.

/**
 * 先网络再缓存:先请求网络,失败则请求缓存
 */
private void networkThenCache() {
    OkHttpUtil.Builder().setCacheType(CacheType.NETWORK_THEN_CACHE).build(this).doGetAsync(HttpInfo.Builder().setUrl(url).build(), new Callback() {

        @Override
        public void onSuccess(HttpInfo info) throws IOException {
            String result = info.getRetDetail();
            resultTV.setText("NETWORK_THEN_CACHE:" + result);
            setFromCacheTV(info);
        }

        @Override
        public void onFailure(HttpInfo info) throws IOException {
            resultTV.setText("NETWORK_THEN_CACHE:" + info.getRetDetail());
        }
    });
    needDeleteCache(true);
}
Also used : HttpInfo(com.okhttplib.HttpInfo) Callback(com.okhttplib.callback.Callback) IOException(java.io.IOException)

Example 5 with HttpInfo

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

the class MainActivity method async.

/**
 * 异步请求:回调方法可以直接操作UI
 */
private void async() {
    doHttpAsync(HttpInfo.Builder().setUrl(url).setRequestType(// 设置请求方式
    RequestType.GET).addHead("head", // 添加头参数
    "test").addParam("param", // 添加接口参数
    "test").setDelayExec(2, // 延迟2秒执行
    TimeUnit.SECONDS).build(), new Callback() {

        @Override
        public void onFailure(HttpInfo info) throws IOException {
            String result = info.getRetDetail();
            resultTV.setText("异步请求失败:" + result);
        }

        @Override
        public void onSuccess(HttpInfo info) throws IOException {
            String result = info.getRetDetail();
            resultTV.setText("异步请求成功:" + result);
            // GSon解析
            TimeAndDate time = info.getRetDetail(TimeAndDate.class);
            LogUtil.d("MainActivity", time.getResult().toString());
            setFromCacheTV(info);
        }
    });
    needDeleteCache(true);
}
Also used : HttpInfo(com.okhttplib.HttpInfo) Callback(com.okhttplib.callback.Callback) TimeAndDate(com.okhttp3.bean.TimeAndDate) IOException(java.io.IOException)

Aggregations

HttpInfo (com.okhttplib.HttpInfo)23 IOException (java.io.IOException)14 ProgressCallback (com.okhttplib.callback.ProgressCallback)10 Callback (com.okhttplib.callback.Callback)7 SocketTimeoutException (java.net.SocketTimeoutException)7 DownloadFileInfo (com.okhttplib.bean.DownloadFileInfo)4 SocketException (java.net.SocketException)4 Request (okhttp3.Request)4 Response (okhttp3.Response)4 ProgressResponseBody (com.okhttplib.progress.ProgressResponseBody)3 File (java.io.File)3 RandomAccessFile (java.io.RandomAccessFile)3 UnknownHostException (java.net.UnknownHostException)3 Call (okhttp3.Call)3 NetworkOnMainThreadException (android.os.NetworkOnMainThreadException)2 CallbackMessage (com.okhttplib.bean.CallbackMessage)2 UploadFileInfo (com.okhttplib.bean.UploadFileInfo)2 BaseCallback (com.okhttplib.callback.BaseCallback)2 BufferedInputStream (java.io.BufferedInputStream)2 InputStream (java.io.InputStream)2