Search in sources :

Example 1 with Response

use of com.lzy.okgo.model.Response in project okhttp-OkGo by jeasonlzy.

the class CacheCall method execute.

@Override
public void execute(AbsCallback<T> callback) {
    synchronized (this) {
        if (executed)
            throw new IllegalStateException("Already executed.");
        executed = true;
    }
    mCallback = callback;
    if (mCallback == null)
        mCallback = new AbsCallbackWrapper<>();
    //请求执行前UI线程调用
    mCallback.onBefore(baseRequest);
    //请求之前获取缓存信息,添加缓存头和其他的公共头
    if (baseRequest.getCacheKey() == null)
        baseRequest.setCacheKey(HttpUtils.createUrlFromParams(baseRequest.getBaseUrl(), baseRequest.getParams().urlParamsMap));
    if (baseRequest.getCacheMode() == null)
        baseRequest.setCacheMode(CacheMode.NO_CACHE);
    //无缓存模式,不需要进入缓存逻辑
    final CacheMode cacheMode = baseRequest.getCacheMode();
    if (cacheMode != CacheMode.NO_CACHE) {
        //noinspection unchecked
        cacheEntity = (CacheEntity<T>) CacheManager.INSTANCE.get(baseRequest.getCacheKey());
        //检查缓存的有效时间,判断缓存是否已经过期
        if (cacheEntity != null && cacheEntity.checkExpire(cacheMode, baseRequest.getCacheTime(), System.currentTimeMillis())) {
            cacheEntity.setExpire(true);
        }
        HeaderParser.addCacheHeaders(baseRequest, cacheEntity, cacheMode);
    }
    //构建请求
    RequestBody requestBody = baseRequest.generateRequestBody();
    final Request request = baseRequest.generateRequest(baseRequest.wrapRequestBody(requestBody));
    rawCall = baseRequest.generateCall(request);
    if (cacheMode == CacheMode.IF_NONE_CACHE_REQUEST) {
        //如果没有缓存,或者缓存过期,就请求网络,否者直接使用缓存
        if (cacheEntity != null && !cacheEntity.isExpire()) {
            T data = cacheEntity.getData();
            HttpHeaders headers = cacheEntity.getResponseHeaders();
            if (data == null || headers == null) {
                //由于没有序列化等原因,可能导致数据为空
                sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
            } else {
                sendSuccessResultCallback(true, data, rawCall, null);
                //获取缓存成功,不请求网络
                return;
            }
        } else {
            sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
        }
    } else if (cacheMode == CacheMode.FIRST_CACHE_THEN_REQUEST) {
        //先使用缓存,不管是否存在,仍然请求网络
        if (cacheEntity != null && !cacheEntity.isExpire()) {
            T data = cacheEntity.getData();
            HttpHeaders headers = cacheEntity.getResponseHeaders();
            if (data == null || headers == null) {
                //由于没有序列化等原因,可能导致数据为空
                sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
            } else {
                sendSuccessResultCallback(true, data, rawCall, null);
            }
        } else {
            sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
        }
    }
    if (canceled) {
        rawCall.cancel();
    }
    currentRetryCount = 0;
    rawCall.enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(okhttp3.Call call, IOException e) {
            if (e instanceof SocketTimeoutException && currentRetryCount < baseRequest.getRetryCount()) {
                //超时重试处理
                currentRetryCount++;
                okhttp3.Call newCall = baseRequest.generateCall(call.request());
                newCall.enqueue(this);
            } else {
                mCallback.parseError(call, e);
                //请求失败,一般为url地址错误,网络错误等,并且过滤用户主动取消的网络请求
                if (!call.isCanceled()) {
                    sendFailResultCallback(false, call, null, e);
                }
            }
        }

        @Override
        public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
            int responseCode = response.code();
            //304缓存数据
            if (responseCode == 304 && cacheMode == CacheMode.DEFAULT) {
                if (cacheEntity == null) {
                    sendFailResultCallback(true, call, response, OkGoException.INSTANCE("服务器响应码304,但是客户端没有缓存!"));
                } else {
                    T data = cacheEntity.getData();
                    HttpHeaders headers = cacheEntity.getResponseHeaders();
                    if (data == null || headers == null) {
                        //由于没有序列化等原因,可能导致数据为空
                        sendFailResultCallback(true, call, response, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
                    } else {
                        sendSuccessResultCallback(true, data, call, response);
                    }
                }
                return;
            }
            //响应失败,一般为服务器内部错误,或者找不到页面等
            if (responseCode == 404 || responseCode >= 500) {
                sendFailResultCallback(false, call, response, OkGoException.INSTANCE("服务器数据异常!"));
                return;
            }
            try {
                Response<T> parseResponse = parseResponse(response);
                T data = parseResponse.body();
                //网络请求成功,保存缓存数据
                handleCache(response.headers(), data);
                //网络请求成功回调
                sendSuccessResultCallback(false, data, call, response);
            } catch (Exception e) {
                //一般为服务器响应成功,但是数据解析错误
                sendFailResultCallback(false, call, response, e);
            }
        }
    });
}
Also used : HttpHeaders(com.lzy.okgo.model.HttpHeaders) Request(okhttp3.Request) BaseRequest(com.lzy.okgo.request.BaseRequest) CacheMode(com.lzy.okgo.cache.CacheMode) IOException(java.io.IOException) OkGoException(com.lzy.okgo.exception.OkGoException) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) Response(com.lzy.okgo.model.Response) AbsCallbackWrapper(com.lzy.okgo.callback.AbsCallbackWrapper) SocketTimeoutException(java.net.SocketTimeoutException) RequestBody(okhttp3.RequestBody)

Example 2 with Response

use of com.lzy.okgo.model.Response in project BaseProject by feer921.

the class CacheCall method execute.

@Override
public void execute(AbsCallback<T> callback) {
    synchronized (this) {
        if (executed)
            throw new IllegalStateException("Already executed.");
        executed = true;
    }
    mCallback = callback;
    if (mCallback == null)
        mCallback = new AbsCallbackWrapper<>();
    // 请求执行前UI线程调用
    mCallback.onBefore(baseRequest);
    // 请求之前获取缓存信息,添加缓存头和其他的公共头
    if (baseRequest.getCacheKey() == null)
        baseRequest.setCacheKey(HttpUtils.createUrlFromParams(baseRequest.getBaseUrl(), baseRequest.getParams().urlParamsMap));
    if (baseRequest.getCacheMode() == null)
        baseRequest.setCacheMode(CacheMode.NO_CACHE);
    // 无缓存模式,不需要进入缓存逻辑
    final CacheMode cacheMode = baseRequest.getCacheMode();
    if (cacheMode != CacheMode.NO_CACHE) {
        // noinspection unchecked
        cacheEntity = (CacheEntity<T>) CacheManager.INSTANCE.get(baseRequest.getCacheKey());
        // 检查缓存的有效时间,判断缓存是否已经过期
        if (cacheEntity != null && cacheEntity.checkExpire(cacheMode, baseRequest.getCacheTime(), System.currentTimeMillis())) {
            cacheEntity.setExpire(true);
        }
        HeaderParser.addCacheHeaders(baseRequest, cacheEntity, cacheMode);
    }
    // 构建请求
    RequestBody requestBody = baseRequest.generateRequestBody();
    final Request request = baseRequest.generateRequest(baseRequest.wrapRequestBody(requestBody));
    rawCall = baseRequest.generateCall(request);
    if (cacheMode == CacheMode.IF_NONE_CACHE_REQUEST) {
        // 如果没有缓存,或者缓存过期,就请求网络,否者直接使用缓存
        if (cacheEntity != null && !cacheEntity.isExpire()) {
            T data = cacheEntity.getData();
            HttpHeaders headers = cacheEntity.getResponseHeaders();
            if (data == null || headers == null) {
                // 由于没有序列化等原因,可能导致数据为空
                sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
            } else {
                sendSuccessResultCallback(true, data, rawCall, null);
                // 获取缓存成功,不请求网络
                return;
            }
        } else {
            sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
        }
    } else if (cacheMode == CacheMode.FIRST_CACHE_THEN_REQUEST) {
        // 先使用缓存,不管是否存在,仍然请求网络
        if (cacheEntity != null && !cacheEntity.isExpire()) {
            T data = cacheEntity.getData();
            HttpHeaders headers = cacheEntity.getResponseHeaders();
            if (data == null || headers == null) {
                // 由于没有序列化等原因,可能导致数据为空
                sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
            } else {
                sendSuccessResultCallback(true, data, rawCall, null);
            }
        } else {
            sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
        }
    }
    if (canceled) {
        rawCall.cancel();
    }
    currentRetryCount = 0;
    rawCall.enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(okhttp3.Call call, IOException e) {
            if (e instanceof SocketTimeoutException && currentRetryCount < baseRequest.getRetryCount()) {
                // 超时重试处理
                currentRetryCount++;
                okhttp3.Call newCall = baseRequest.generateCall(call.request());
                newCall.enqueue(this);
            } else {
                mCallback.parseError(call, e);
                // 请求失败,一般为url地址错误,网络错误等,并且过滤用户主动取消的网络请求
                if (!call.isCanceled()) {
                    sendFailResultCallback(false, call, null, e);
                }
            }
        }

        @Override
        public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
            int responseCode = response.code();
            // 304缓存数据
            if (responseCode == 304 && cacheMode == CacheMode.DEFAULT) {
                if (cacheEntity == null) {
                    sendFailResultCallback(true, call, response, OkGoException.INSTANCE("服务器响应码304,但是客户端没有缓存!"));
                } else {
                    T data = cacheEntity.getData();
                    HttpHeaders headers = cacheEntity.getResponseHeaders();
                    if (data == null || headers == null) {
                        // 由于没有序列化等原因,可能导致数据为空
                        sendFailResultCallback(true, call, response, OkGoException.INSTANCE("没有获取到缓存,或者缓存已经过期!"));
                    } else {
                        sendSuccessResultCallback(true, data, call, response);
                    }
                }
                return;
            }
            // 响应失败,一般为服务器内部错误,或者找不到页面等
            if (responseCode == 404 || responseCode >= 500) {
                sendFailResultCallback(false, call, response, OkGoException.INSTANCE("服务器数据异常!"));
                return;
            }
            try {
                Response<T> parseResponse = parseResponse(response);
                T data = parseResponse.body();
                // 网络请求成功,保存缓存数据
                handleCache(response.headers(), data);
                // 网络请求成功回调
                sendSuccessResultCallback(false, data, call, response);
            } catch (Exception e) {
                // 一般为服务器响应成功,但是数据解析错误
                sendFailResultCallback(false, call, response, e);
            }
        }
    });
}
Also used : HttpHeaders(com.lzy.okgo.model.HttpHeaders) Request(okhttp3.Request) BaseRequest(com.lzy.okgo.request.BaseRequest) CacheMode(com.lzy.okgo.cache.CacheMode) IOException(java.io.IOException) OkGoException(com.lzy.okgo.exception.OkGoException) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) Response(com.lzy.okgo.model.Response) AbsCallbackWrapper(com.lzy.okgo.callback.AbsCallbackWrapper) SocketTimeoutException(java.net.SocketTimeoutException) RequestBody(okhttp3.RequestBody)

Example 3 with Response

use of com.lzy.okgo.model.Response in project okhttp-OkGo by jeasonlzy.

the class RxCommonActivity method upJson.

@OnClick(R.id.upJson)
public void upJson(View view) {
    HashMap<String, String> params = new HashMap<>();
    params.put("key1", "value1");
    params.put("key2", "这里是需要提交的json格式数据");
    params.put("key3", "也可以使用三方工具将对象转成json字符串");
    params.put("key4", "其实你怎么高兴怎么写都行");
    JSONObject jsonObject = new JSONObject(params);
    // 
    OkGo.<String>post(Urls.URL_TEXT_UPLOAD).headers("aaa", // 
    "111").upJson(// 
    jsonObject).converter(// 
    new StringConvert()).adapt(// 
    new ObservableResponse<String>()).subscribeOn(// 
    Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {

        @Override
        public void accept(@NonNull Disposable disposable) throws Exception {
            showLoading();
        }
    }).observeOn(// 
    AndroidSchedulers.mainThread()).subscribe(new Observer<Response<String>>() {

        @Override
        public void onSubscribe(@NonNull Disposable d) {
            addDisposable(d);
        }

        @Override
        public void onNext(@NonNull Response<String> response) {
            handleResponse(response);
        }

        @Override
        public void onError(@NonNull Throwable e) {
            e.printStackTrace();
            showToast("请求失败");
            handleError(null);
        }

        @Override
        public void onComplete() {
            dismissLoading();
        }
    });
}
Also used : StringConvert(com.lzy.okgo.convert.StringConvert) Disposable(io.reactivex.disposables.Disposable) HashMap(java.util.HashMap) Response(com.lzy.okgo.model.Response) ObservableResponse(com.lzy.okrx2.adapter.ObservableResponse) LzyResponse(com.lzy.demo.model.LzyResponse) JSONObject(org.json.JSONObject) OnClick(butterknife.OnClick)

Example 4 with Response

use of com.lzy.okgo.model.Response in project okhttp-OkGo by jeasonlzy.

the class RxFormUploadActivity method formUpload1.

@OnClick(R.id.formUpload1)
public void formUpload1(View view) {
    ArrayList<File> files = new ArrayList<>();
    if (imageItems != null && imageItems.size() > 0) {
        for (int i = 0; i < imageItems.size(); i++) {
            files.add(new File(imageItems.get(i).path));
        }
    }
    // 拼接参数
    // 
    OkGo.<String>post(Urls.URL_FORM_UPLOAD).tag(// 
    this).headers("header1", // 
    "headerValue1").headers("header2", // 
    "headerValue2").params("param1", // 
    "paramValue1").params("param2", // 
    "paramValue2").addFileParams("file", // 
    files).converter(// 
    new StringConvert()).adapt(// 
    new ObservableResponse<String>()).doOnSubscribe(new Consumer<Disposable>() {

        @Override
        public void accept(@NonNull Disposable disposable) throws Exception {
            btnFormUpload1.setText("正在上传中...\n使用Rx方式做进度监听稍显麻烦,推荐使用方式2");
        }
    }).observeOn(// 
    AndroidSchedulers.mainThread()).subscribe(new Observer<Response<String>>() {

        @Override
        public void onSubscribe(@NonNull Disposable d) {
            addDisposable(d);
        }

        @Override
        public void onNext(@NonNull Response<String> response) {
            btnFormUpload1.setText("上传完成");
            handleResponse(response);
        }

        @Override
        public void onError(@NonNull Throwable e) {
            e.printStackTrace();
            btnFormUpload1.setText("上传出错");
            showToast(e.getMessage());
            handleError(null);
        }

        @Override
        public void onComplete() {
        }
    });
}
Also used : StringConvert(com.lzy.okgo.convert.StringConvert) Disposable(io.reactivex.disposables.Disposable) ArrayList(java.util.ArrayList) Response(com.lzy.okgo.model.Response) ObservableResponse(com.lzy.okrx2.adapter.ObservableResponse) ObservableResponse(com.lzy.okrx2.adapter.ObservableResponse) File(java.io.File) OnClick(butterknife.OnClick)

Example 5 with Response

use of com.lzy.okgo.model.Response in project okhttp-OkGo by jeasonlzy.

the class CallArbiter method emitResponse.

private void emitResponse(List<Response<T>> responseList) {
    try {
        synchronized (this) {
            Iterator<Response<T>> iterator = responseList.iterator();
            while (iterator.hasNext()) {
                Response<T> next = iterator.next();
                iterator.remove();
                if (!isUnsubscribed()) {
                    subscriber.onNext(next);
                } else {
                    return;
                }
            }
        }
    } catch (OnCompletedFailedException | OnErrorFailedException | OnErrorNotImplementedException e) {
        RxJavaHooks.getOnError().call(e);
    } catch (Throwable t) {
        Exceptions.throwIfFatal(t);
        try {
            subscriber.onError(t);
        } catch (OnCompletedFailedException | OnErrorFailedException | OnErrorNotImplementedException e) {
            RxJavaHooks.getOnError().call(e);
        } catch (Throwable inner) {
            Exceptions.throwIfFatal(inner);
            RxJavaHooks.getOnError().call(new CompositeException(t, inner));
        }
    }
}
Also used : Response(com.lzy.okgo.model.Response) OnCompletedFailedException(rx.exceptions.OnCompletedFailedException) CompositeException(rx.exceptions.CompositeException) OnErrorNotImplementedException(rx.exceptions.OnErrorNotImplementedException) OnErrorFailedException(rx.exceptions.OnErrorFailedException)

Aggregations

Response (com.lzy.okgo.model.Response)5 OnClick (butterknife.OnClick)2 CacheMode (com.lzy.okgo.cache.CacheMode)2 AbsCallbackWrapper (com.lzy.okgo.callback.AbsCallbackWrapper)2 StringConvert (com.lzy.okgo.convert.StringConvert)2 OkGoException (com.lzy.okgo.exception.OkGoException)2 HttpHeaders (com.lzy.okgo.model.HttpHeaders)2 BaseRequest (com.lzy.okgo.request.BaseRequest)2 ObservableResponse (com.lzy.okrx2.adapter.ObservableResponse)2 Disposable (io.reactivex.disposables.Disposable)2 IOException (java.io.IOException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 Request (okhttp3.Request)2 RequestBody (okhttp3.RequestBody)2 LzyResponse (com.lzy.demo.model.LzyResponse)1 File (java.io.File)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 JSONObject (org.json.JSONObject)1 CompositeException (rx.exceptions.CompositeException)1