Example usage for com.squareup.okhttp Interceptor Interceptor

List of usage examples for com.squareup.okhttp Interceptor Interceptor

Introduction

In this page you can find the example usage for com.squareup.okhttp Interceptor Interceptor.

Prototype

Interceptor

Source Link

Usage

From source file:com.liferay.mobile.screens.context.LiferayServerContext.java

License:Open Source License

public static OkHttpClient getOkHttpClientNoCache() {
    OkHttpClient noCacheClient = getOkHttpClient().clone();
    noCacheClient.interceptors().add(new Interceptor() {
        @Override/*from   ww w. ja  va 2 s. c  om*/
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            Request newRequest = originalRequest.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();

            return chain.proceed(newRequest);
        }
    });

    return noCacheClient;
}

From source file:com.maxleapmobile.gitmaster.api.ApiManager.java

License:Open Source License

private ApiManager() {
    mContext = GithubApplication.getInstance();

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
    okHttpClient.interceptors().add(new Interceptor() {
        @Override/*from w ww . j  a  v  a 2  s.c o m*/
        public Response intercept(Chain chain) throws IOException {
            mAccessToken = PreferenceUtil.getString(mContext, Const.ACCESS_TOKEN_KEY, null);
            HttpUrl url;
            if (mAccessToken != null) {
                url = chain.request().httpUrl().newBuilder().addQueryParameter("access_token", mAccessToken)
                        .build();
            } else {
                url = chain.request().httpUrl();
            }

            Request request = chain.request();
            Request newRequest;
            newRequest = request.newBuilder().url(url).addHeader("User-Agent", USER_AGENT)
                    .addHeader("Accept", ACCEPT).build();
            return chain.proceed(newRequest);
        }
    });
    mRetrofit = new Retrofit.Builder().baseUrl(API_URL).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    mGithubApi = mRetrofit.create(GithubApi.class);
}

From source file:com.microsoft.rest.CredentialsTests.java

License:Open Source License

@Test
public void basicCredentialsTest() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };//from   w w w  .j av a 2  s. c o  m
    BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials("user", "pass");
    credentials.applyCredentialsFilter(serviceClient.client);
    serviceClient.getClientInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String header = chain.request().header("Authorization");
            Assert.assertEquals("Basic dXNlcjpwYXNz", header);
            return new Response.Builder().request(chain.request()).code(200).protocol(Protocol.HTTP_1_1)
                    .build();
        }
    });
}

From source file:com.microsoft.rest.CredentialsTests.java

License:Open Source License

@Test
public void tokenCredentialsTest() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };//  w  ww .  ja va  2s  .co  m
    TokenCredentials credentials = new TokenCredentials(null, "this_is_a_token");
    credentials.applyCredentialsFilter(serviceClient.client);
    serviceClient.getClientInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String header = chain.request().header("Authorization");
            Assert.assertEquals("Bearer this_is_a_token", header);
            return new Response.Builder().request(chain.request()).code(200).protocol(Protocol.HTTP_1_1)
                    .build();
        }
    });
}

From source file:com.microsoft.rest.RetryHandlerTests.java

License:Open Source License

@Test
public void exponentialRetryEndOn501() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };//from  w  w  w  . j  ava2  s .c o m
    serviceClient.getClientInterceptors().add(new Interceptor() {
        // Send 408, 500, 502, all retried, with a 501 ending
        private int[] codes = new int[] { 408, 500, 502, 501 };
        private int count = 0;

        @Override
        public Response intercept(Chain chain) throws IOException {
            return new Response.Builder().request(chain.request()).code(codes[count++])
                    .protocol(Protocol.HTTP_1_1).build();
        }
    });
    Response response = serviceClient.client
            .newCall(new Request.Builder().url("http://localhost").get().build()).execute();
    Assert.assertEquals(501, response.code());
}

From source file:com.microsoft.rest.RetryHandlerTests.java

License:Open Source License

@Test
public void exponentialRetryMax() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };//w  w w  .j  av  a2 s.  c o  m
    serviceClient.getClientInterceptors().add(new Interceptor() {
        // Send 500 until max retry is hit
        private int count = 0;

        @Override
        public Response intercept(Chain chain) throws IOException {
            Assert.assertTrue(count++ < 5);
            return new Response.Builder().request(chain.request()).code(500).protocol(Protocol.HTTP_1_1)
                    .build();
        }
    });
    Response response = serviceClient.client
            .newCall(new Request.Builder().url("http://localhost").get().build()).execute();
    Assert.assertEquals(500, response.code());
}

From source file:com.microsoft.rest.ServiceClientTests.java

License:Open Source License

@Test
public void filterTests() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };/*from w w w.  ja  v  a 2  s .co m*/
    serviceClient.getClientInterceptors().add(0, new FirstFilter());
    serviceClient.getClientInterceptors().add(1, new SecondFilter());
    serviceClient.getClientInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Assert.assertEquals("1", chain.request().header("filter1"));
            Assert.assertEquals("2", chain.request().header("filter2"));
            return chain.proceed(chain.request());
        }
    });
}

From source file:com.microsoft.rest.UserAgentTests.java

License:Open Source License

@Test
public void defaultUserAgentTests() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };/* w  ww  . j a v a2s.  c o m*/
    serviceClient.getClientInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String header = chain.request().header("User-Agent");
            Assert.assertEquals("AutoRest-Java", header);
            return new Response.Builder().request(chain.request()).code(200).protocol(Protocol.HTTP_1_1)
                    .build();
        }
    });
}

From source file:com.microsoft.rest.UserAgentTests.java

License:Open Source License

@Test
public void customUserAgentTests() throws Exception {
    ServiceClient serviceClient = new ServiceClient() {
    };//from  www .  j a  v  a2  s.  c  o m
    serviceClient.getClientInterceptors().add(new UserAgentInterceptor("Awesome"));
    serviceClient.getClientInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String header = chain.request().header("User-Agent");
            Assert.assertEquals("Awesome", header);
            return new Response.Builder().request(chain.request()).code(200).protocol(Protocol.HTTP_1_1)
                    .build();
        }
    });
}

From source file:com.parse.ParseOkHttpClient.java

License:Open Source License

/**
 * For OKHttpClient, since it does not expose any interface for us to check the raw response
 * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
 * we use OKHttp inner interceptor list.
 * @param parseNetworkInterceptor/*from w  ww . j av  a  2s .c om*/
 */
@Override
/* package */ void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
    okHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(final Chain okHttpChain) throws IOException {
            Request okHttpRequest = okHttpChain.request();
            // Transfer OkHttpRequest to ParseHttpRequest
            final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
            // Capture OkHttpResponse
            final Capture<Response> okHttpResponseCapture = new Capture<>();
            final ParseHttpResponse parseResponse = parseNetworkInterceptor
                    .intercept(new ParseNetworkInterceptor.Chain() {
                        @Override
                        public ParseHttpRequest getRequest() {
                            return parseRequest;
                        }

                        @Override
                        public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
                            // Use OKHttpClient to send request
                            Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
                            Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
                            okHttpResponseCapture.set(okHttpResponse);
                            return getResponse(okHttpResponse);
                        }
                    });
            final Response okHttpResponse = okHttpResponseCapture.get();
            // Ideally we should build newOkHttpResponse only based on parseResponse, however
            // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
            // we rely on the okHttpResponse to generate the builder and change the necessary info
            // inside
            Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
            // Set status
            newOkHttpResponseBuilder.code(parseResponse.getStatusCode())
                    .message(parseResponse.getReasonPhrase());
            // Set headers
            if (parseResponse.getAllHeaders() != null) {
                for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
                    newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
                }
            }
            // Set body
            newOkHttpResponseBuilder.body(new ResponseBody() {
                @Override
                public MediaType contentType() {
                    if (parseResponse.getContentType() == null) {
                        return null;
                    }
                    return MediaType.parse(parseResponse.getContentType());
                }

                @Override
                public long contentLength() throws IOException {
                    return parseResponse.getTotalSize();
                }

                @Override
                public BufferedSource source() throws IOException {
                    // We need to use the proxy stream from interceptor to replace the origin network
                    // stream, so when the stream is read by Parse, the network stream is proxyed in the
                    // interceptor.
                    if (parseResponse.getContent() == null) {
                        return null;
                    }
                    return Okio.buffer(Okio.source(parseResponse.getContent()));
                }
            });

            return newOkHttpResponseBuilder.build();
        }
    });
}