Search in sources :

Example 1 with Callback

use of okhttp3.Callback 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 Callback

use of okhttp3.Callback in project lottie-android by airbnb.

the class AnimationFragment method loadUrl.

private void loadUrl(String url) {
    Request request;
    try {
        request = new Request.Builder().url(url).build();
    } catch (IllegalArgumentException e) {
        onLoadError();
        return;
    }
    if (client == null) {
        client = new OkHttpClient();
    }
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            onLoadError();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) {
                onLoadError();
            }
            try {
                JSONObject json = new JSONObject(response.body().string());
                LottieComposition.Factory.fromJson(getResources(), json, new OnCompositionLoadedListener() {

                    @Override
                    public void onCompositionLoaded(LottieComposition composition) {
                        setComposition(composition, "Network Animation");
                    }
                });
            } catch (JSONException e) {
                onLoadError();
            }
        }
    });
}
Also used : Call(okhttp3.Call) OnCompositionLoadedListener(com.airbnb.lottie.OnCompositionLoadedListener) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) LottieComposition(com.airbnb.lottie.LottieComposition)

Example 3 with Callback

use of okhttp3.Callback in project zipkin by openzipkin.

the class HttpCallTest method propagatesOnDispatcherThreadWhenFatal.

@Test
public void propagatesOnDispatcherThreadWhenFatal() throws Exception {
    mws.enqueue(new MockResponse());
    http.newCall(request, b -> {
        throw new LinkageError();
    }).submit(callback);
    SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter();
    try {
        timeLimiter.callWithTimeout(callback::get, 100, TimeUnit.MILLISECONDS, true);
        failBecauseExceptionWasNotThrown(UncheckedTimeoutException.class);
    } catch (UncheckedTimeoutException expected) {
    }
}
Also used : Request(okhttp3.Request) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IOException(java.io.IOException) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Rule(org.junit.Rule) After(org.junit.After) MockWebServer(okhttp3.mockwebserver.MockWebServer) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) MockResponse(okhttp3.mockwebserver.MockResponse) CallbackCaptor(zipkin.internal.CallbackCaptor) Assertions.failBecauseExceptionWasNotThrown(org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown) MockResponse(okhttp3.mockwebserver.MockResponse) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) Test(org.junit.Test)

Example 4 with Callback

use of okhttp3.Callback in project zipkin by openzipkin.

the class HttpCallTest method executionException_conversionException.

@Test
public void executionException_conversionException() throws Exception {
    mws.enqueue(new MockResponse());
    http.newCall(request, b -> {
        throw new IllegalArgumentException("eeek");
    }).submit(callback);
    try {
        callback.get();
        failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException expected) {
        assertThat(expected).isInstanceOf(IllegalArgumentException.class);
    }
}
Also used : Request(okhttp3.Request) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IOException(java.io.IOException) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Rule(org.junit.Rule) After(org.junit.After) MockWebServer(okhttp3.mockwebserver.MockWebServer) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) MockResponse(okhttp3.mockwebserver.MockResponse) CallbackCaptor(zipkin.internal.CallbackCaptor) Assertions.failBecauseExceptionWasNotThrown(org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.junit.Test)

Example 5 with Callback

use of okhttp3.Callback in project zipkin by openzipkin.

the class HttpBulkSpanIndexerTest method doesntWriteSpanId.

@Test
public void doesntWriteSpanId() throws Exception {
    es.enqueue(new MockResponse());
    indexer.add("test_zipkin_http-2016-10-01", TestObjects.LOTS_OF_SPANS[0], (Long) null);
    indexer.execute(callback);
    callback.get();
    RecordedRequest request = es.takeRequest();
    assertThat(request.getBody().readByteString().utf8()).doesNotContain("\"_id\"");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.junit.Test)

Aggregations

ResponseBody (okhttp3.ResponseBody)248 Response (okhttp3.Response)214 Request (okhttp3.Request)208 IOException (java.io.IOException)203 Callback (okhttp3.Callback)172 DateTimeRfc1123 (com.microsoft.rest.DateTimeRfc1123)166 Call (okhttp3.Call)166 DateTime (org.joda.time.DateTime)166 ServiceCall (com.microsoft.rest.ServiceCall)140 Test (org.junit.Test)119 List (java.util.List)101 Call (retrofit2.Call)87 MockResponse (okhttp3.mockwebserver.MockResponse)72 RequestBody (okhttp3.RequestBody)62 OkHttpClient (okhttp3.OkHttpClient)61 LinkHeaders (com.instructure.canvasapi2.utils.LinkHeaders)57 GsonBuilder (com.google.gson.GsonBuilder)53 Retrofit (retrofit2.Retrofit)53 PagedList (com.microsoft.azure.PagedList)52 ServiceResponseWithHeaders (com.microsoft.rest.ServiceResponseWithHeaders)52