Search in sources :

Example 46 with Interceptor

use of okhttp3.Interceptor in project MVPArms by JessYanCoding.

the class WEApplication method getGlobeConfigModule.

/**
     * app的全局配置信息封装进module(使用Dagger注入到需要配置信息的地方)
     * GlobeHttpHandler是在NetworkInterceptor中拦截数据
     * 如果想将请求参数加密,则必须在Interceptor中对参数进行处理,GlobeConfigModule.addInterceptor可以添加Interceptor
     * @return
     */
@Override
protected GlobeConfigModule getGlobeConfigModule() {
    return GlobeConfigModule.buidler().baseurl(Api.APP_DOMAIN).globeHttpHandler(new // 这里可以提供一个全局处理http响应结果的处理类,
    GlobeHttpHandler() {

        // 这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
        @Override
        public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
            //重新请求token,并重新执行请求
            try {
                if (!TextUtils.isEmpty(httpResult)) {
                    JSONArray array = new JSONArray(httpResult);
                    JSONObject object = (JSONObject) array.get(0);
                    String login = object.getString("login");
                    String avatar_url = object.getString("avatar_url");
                    Timber.tag(TAG).w("result ------>" + login + "    ||   avatar_url------>" + avatar_url);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return response;
            }
            //如果不需要返回新的结果,则直接把response参数返回出去
            return response;
        }

        // 这里可以在请求服务器之前可以拿到request,做一些操作比如给request统一添加token或者header
        @Override
        public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
            //                .build();
            return request;
        }
    }).responseErroListener(new ResponseErroListener() {

        //     用来提供处理所有错误的监听
        //     rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效
        @Override
        public void handleResponseError(Context context, Exception e) {
            Timber.tag(TAG).w("------------>" + e.getMessage());
            UiUtils.SnackbarText("net error");
        }
    }).build();
}
Also used : Context(android.content.Context) JSONArray(org.json.JSONArray) Request(okhttp3.Request) JSONException(org.json.JSONException) ResponseErroListener(me.jessyan.rxerrorhandler.handler.listener.ResponseErroListener) JSONException(org.json.JSONException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) Interceptor(okhttp3.Interceptor)

Example 47 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class RealCall method getResponseWithInterceptorChain.

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
        interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
}
Also used : ConnectInterceptor(okhttp3.internal.connection.ConnectInterceptor) RealInterceptorChain(okhttp3.internal.http.RealInterceptorChain) ArrayList(java.util.ArrayList) CallServerInterceptor(okhttp3.internal.http.CallServerInterceptor) BridgeInterceptor(okhttp3.internal.http.BridgeInterceptor) CacheInterceptor(okhttp3.internal.cache.CacheInterceptor) ConnectInterceptor(okhttp3.internal.connection.ConnectInterceptor) RetryAndFollowUpInterceptor(okhttp3.internal.http.RetryAndFollowUpInterceptor) CallServerInterceptor(okhttp3.internal.http.CallServerInterceptor) BridgeInterceptor(okhttp3.internal.http.BridgeInterceptor) CacheInterceptor(okhttp3.internal.cache.CacheInterceptor)

Example 48 with Interceptor

use of okhttp3.Interceptor in project retrofit by square.

the class CallTest method conversionProblemIncomingMaskedByConverterIsUnwrapped.

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = //
    new OkHttpClient.Builder().addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {

                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    }).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client).addConverterFactory(new ToStringConverterFactory() {

        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            return new Converter<ResponseBody, String>() {

                @Override
                public String convert(ResponseBody value) throws IOException {
                    try {
                        return value.string();
                    } catch (IOException e) {
                        // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                        throw new RuntimeException("wrapper", e);
                    }
                }
            };
        }
    }).build();
    Service example = retrofit.create(Service.class);
    server.enqueue(new MockResponse().setBody("Hi"));
    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) OkHttpClient(okhttp3.OkHttpClient) ForwardingSource(okio.ForwardingSource) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) Interceptor(okhttp3.Interceptor) BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 49 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class CacheTest method networkInterceptorInvokedForConditionalGet.

@Test
public void networkInterceptorInvokedForConditionalGet() throws Exception {
    server.enqueue(new MockResponse().addHeader("ETag: v1").setBody("A"));
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    // Seed the cache.
    HttpUrl url = server.url("/");
    assertEquals("A", get(url).body().string());
    final AtomicReference<String> ifNoneMatch = new AtomicReference<>();
    client = client.newBuilder().addNetworkInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match"));
            return chain.proceed(chain.request());
        }
    }).build();
    // Confirm the value is cached and intercepted.
    assertEquals("A", get(url).body().string());
    assertEquals("v1", ifNoneMatch.get());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) Test(org.junit.Test)

Example 50 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class CacheTest method networkInterceptorNotInvokedForFullyCached.

@Test
public void networkInterceptorNotInvokedForFullyCached() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").setBody("A"));
    // Seed the cache.
    HttpUrl url = server.url("/");
    assertEquals("A", get(url).body().string());
    // Confirm the interceptor isn't exercised.
    client = client.newBuilder().addNetworkInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            throw new AssertionError();
        }
    }).build();
    assertEquals("A", get(url).body().string());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

IOException (java.io.IOException)37 Interceptor (okhttp3.Interceptor)36 Request (okhttp3.Request)29 MockResponse (okhttp3.mockwebserver.MockResponse)29 Response (okhttp3.Response)25 Test (org.junit.Test)25 OkHttpClient (okhttp3.OkHttpClient)24 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)24 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)9 File (java.io.File)8 Retrofit (retrofit2.Retrofit)8 Provides (dagger.Provides)6 Singleton (javax.inject.Singleton)6 Cache (okhttp3.Cache)5 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)3 InterruptedIOException (java.io.InterruptedIOException)3 Call (okhttp3.Call)3 HttpUrl (okhttp3.HttpUrl)3 NonNull (android.support.annotation.NonNull)2 ANResponse (com.androidnetworking.common.ANResponse)2