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:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

@Test
public void networkInterceptorsObserveNetworkHeaders() throws Exception {
    server.enqueue(new MockResponse().setBody(gzip("abcabcabc")).addHeader("Content-Encoding: gzip"));

    client.networkInterceptors().add(new Interceptor() {
        @Override/*from  w  w w .  j  a va2 s.c  o  m*/
        public Response intercept(Chain chain) throws IOException {
            // The network request has everything: User-Agent, Host, Accept-Encoding.
            Request networkRequest = chain.request();
            assertNotNull(networkRequest.header("User-Agent"));
            assertEquals(server.get().getHostName() + ":" + server.get().getPort(),
                    networkRequest.header("Host"));
            assertNotNull(networkRequest.header("Accept-Encoding"));

            // The network response also has everything, including the raw gzipped content.
            Response networkResponse = chain.proceed(networkRequest);
            assertEquals("gzip", networkResponse.header("Content-Encoding"));
            return networkResponse;
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    // No extra headers in the application's request.
    assertNull(request.header("User-Agent"));
    assertNull(request.header("Host"));
    assertNull(request.header("Accept-Encoding"));

    // No extra headers in the application's response.
    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertNull(request.header("Content-Encoding"));
    assertEquals("abcabcabc", response.body().string());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void rewriteRequestToServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override//from w  ww  .  j  av a2s.  c om
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build());
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Original-Header", "foo")
            .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build();

    FiberOkHttpUtil.executeInFiber(client, request);

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("ABC", recordedRequest.getBody().readUtf8());
    assertEquals("foo", recordedRequest.getHeader("Original-Header"));
    assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted"));
    assertEquals("POST", recordedRequest.getMethod());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void rewriteResponseFromServer(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse().addHeader("Original-Header: foo").setBody("abc"));

    interceptors.add(new Interceptor() {
        @Override/*from  w  w w . ja  v  a2s .  c o m*/
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().body(uppercase(originalResponse.body()))
                    .addHeader("OkHttp-Intercepted", "yep").build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals("ABC", response.body().string());
    assertEquals("yep", response.header("OkHttp-Intercepted"));
    assertEquals("foo", response.header("Original-Header"));
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void multipleInterceptors(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override//from www.j  a  v  a2 s  .  c  om
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Android") // 1. Added first.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Donut") // 4. Added last.
                    .build();
        }
    });
    interceptors.add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Response originalResponse = chain
                    .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Bob") // 2. Added second.
                            .build());
            return originalResponse.newBuilder().addHeader("Response-Interceptor", "Cupcake") // 3. Added third.
                    .build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals(Arrays.asList("Cupcake", "Donut"), response.headers("Response-Interceptor"));

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals(Arrays.asList("Android", "Bob"), recordedRequest.getHeaders().values("Request-Interceptor"));
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

private void asyncInterceptors(List<Interceptor> interceptors) throws Exception {
    server.enqueue(new MockResponse());

    interceptors.add(new Interceptor() {
        @Override//ww w  .j a  v a2  s  .  c  o m
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().addHeader("OkHttp-Intercepted", "yep").build();
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    client.newCall(request).enqueue(callback);

    callback.await(request.url()).assertCode(200).assertHeader("OkHttp-Intercepted", "yep");
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

@Test
public void applicationInterceptorsCanMakeMultipleRequestsToServer() throws Exception {
    server.enqueue(new MockResponse().setBody("a"));
    server.enqueue(new MockResponse().setBody("b"));

    client.interceptors().add(new Interceptor() {
        @Override/* ww  w  . ja  va 2 s  . c  o m*/
        public Response intercept(Chain chain) throws IOException {
            chain.proceed(chain.request());
            return chain.proceed(chain.request());
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals(response.body().string(), "b");
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

/** Make sure interceptors can interact with the OkHttp client. */
@Test/*  w  w  w .  j av a  2 s .co m*/
public void interceptorMakesAnUnrelatedRequest() throws Exception {
    server.enqueue(new MockResponse().setBody("a")); // Fetched by interceptor.
    server.enqueue(new MockResponse().setBody("b")); // Fetched directly.

    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain.request().url().getPath().equals("/b")) {
                Request requestA = new Request.Builder().url(server.getUrl("/a")).build();
                Response responseA = null;
                try {
                    responseA = FiberOkHttpUtil.executeInFiber(client, requestA);
                } catch (InterruptedException ex) {
                    throw new AssertionError(ex);
                }
                assertEquals("a", responseA.body().string());
            }

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

    Request requestB = new Request.Builder().url(server.getUrl("/b")).build();
    Response responseB = FiberOkHttpUtil.executeInFiber(client, requestB);
    assertEquals("b", responseB.body().string());
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

/** Make sure interceptors can interact with the OkHttp client asynchronously. */
@Test//from   ww w.j a  v a 2s .  co  m
public void interceptorMakesAnUnrelatedAsyncRequest() throws Exception {
    server.enqueue(new MockResponse().setBody("a")); // Fetched by interceptor.
    server.enqueue(new MockResponse().setBody("b")); // Fetched directly.

    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain.request().url().getPath().equals("/b")) {
                Request requestA = new Request.Builder().url(server.getUrl("/a")).build();

                try {
                    RecordingCallback callbackA = new RecordingCallback();
                    client.newCall(requestA).enqueue(callbackA);
                    callbackA.await(requestA.url()).assertBody("a");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

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

    Request requestB = new Request.Builder().url(server.getUrl("/b")).build();
    RecordingCallback callbackB = new RecordingCallback();
    client.newCall(requestB).enqueue(callbackB);
    callbackB.await(requestB.url()).assertBody("b");
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

/**
 * When an interceptor throws an unexpected exception, synchronous callers can catch it and deal
 * with it.//  w w w .j  a v  a  2  s.  co m
 *
 * TODO(jwilson): test that resources are not leaked when this happens.
 */
private void interceptorThrowsRuntimeExceptionSynchronous(List<Interceptor> interceptors) throws Exception {
    interceptors.add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            throw new RuntimeException("boom!");
        }
    });

    Request request = new Request.Builder().url(server.getUrl("/")).build();

    try {
        FiberOkHttpUtil.executeInFiber(client, request);
        fail();
    } catch (RuntimeException expected) {
        assertEquals("boom!", expected.getMessage());
    }
}

From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java

License:Open Source License

@Test
public void networkInterceptorModifiedRequestIsReturned()
        throws IOException, InterruptedException, ExecutionException {
    server.enqueue(new MockResponse());

    Interceptor modifyHeaderInterceptor = new Interceptor() {
        @Override/*from   w ww  . ja va2  s  .  c o  m*/
        public Response intercept(Chain chain) throws IOException {
            return chain
                    .proceed(chain.request().newBuilder().header("User-Agent", "intercepted request").build());
        }
    };

    client.networkInterceptors().add(modifyHeaderInterceptor);

    Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "user request")
            .build();

    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertNotNull(response.request().header("User-Agent"));
    assertEquals("user request", response.request().header("User-Agent"));
    assertEquals("intercepted request", response.networkResponse().request().header("User-Agent"));
}