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

/**
 * When an interceptor throws an unexpected exception, asynchronous callers are left hanging. The
 * exception goes to the uncaught exception handler.
 *
 * TODO(jwilson): test that resources are not leaked when this happens.
 *//* www .  j a v  a 2 s.co  m*/
private void interceptorThrowsRuntimeExceptionAsynchronous(List<Interceptor> interceptors) throws Exception {
    interceptors.add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            throw new RuntimeException("boom!");
        }
    });

    ExceptionCatchingExecutor executor = new ExceptionCatchingExecutor();
    client.setDispatcher(new Dispatcher(executor));

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

    assertEquals("boom!", executor.takeException().getMessage());
}

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

License:Apache License

@Test
public void applicationInterceptorsCanShortCircuitResponses() throws Exception {
    server.shutdown(); // Accept no connections.

    Request request = new Request.Builder().url("https://localhost:1/").build();

    final Response interceptorResponse = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1)
            .code(200).message("Intercepted!")
            .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "abc")).build();

    client.interceptors().add(new Interceptor() {
        @Override/*from w w  w.  j av  a 2s . co m*/
        public Response intercept(Chain chain) throws IOException {
            return interceptorResponse;
        }
    });

    Response response = client.newCall(request).execute();
    assertSame(interceptorResponse, response);
}

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

License:Apache License

@Ignore
@Test// w ww. j  a  va  2  s.  c om
public void networkInterceptorsCannotShortCircuitResponses() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(500));

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            return new Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200)
                    .message("Intercepted!")
                    .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "abc")).build();
        }
    };
    client.networkInterceptors().add(interceptor);

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

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must call proceed() exactly once",
                expected.getMessage());
    }
}

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

License:Apache License

@Ignore
@Test/* w  w w .jav a 2s. co m*/
public void networkInterceptorsCannotCallProceedMultipleTimes() throws Exception {
    server.enqueue(new MockResponse());
    server.enqueue(new MockResponse());

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            chain.proceed(chain.request());
            return chain.proceed(chain.request());
        }
    };
    client.networkInterceptors().add(interceptor);

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

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must call proceed() exactly once",
                expected.getMessage());
    }
}

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

License:Apache License

@Ignore
@Test/*ww  w . j  a  va2  s . c o  m*/
public void networkInterceptorsCannotChangeServerAddress() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(500));

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Address address = chain.connection().getRoute().getAddress();
            String sameHost = address.getUriHost();
            int differentPort = address.getUriPort() + 1;
            return chain.proceed(chain.request().newBuilder()
                    .url(HttpUrl.parse("http://" + sameHost + ":" + differentPort + "/")).build());
        }
    };
    client.networkInterceptors().add(interceptor);

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

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must retain the same host and port",
                expected.getMessage());
    }
}

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

License:Apache License

@Test
public void networkInterceptorsHaveConnectionAccess() throws Exception {
    server.enqueue(new MockResponse());

    client.networkInterceptors().add(new Interceptor() {
        @Override//  ww  w  . jav  a  2 s  .  c  o  m
        public Response intercept(Chain chain) throws IOException {
            Connection connection = chain.connection();
            assertNotNull(connection);
            return chain.proceed(chain.request());
        }
    });

    Request request = new Request.Builder().url(server.url("/")).build();
    client.newCall(request).execute();
}

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

License:Apache 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.  ja  v a 2 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.getHostName() + ":" + server.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.url("/")).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 = client.newCall(request).execute();
    assertNull(request.header("Content-Encoding"));
    assertEquals("abcabcabc", response.body().string());
}

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

License:Apache License

@Test
public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
    server.enqueue(new MockResponse());

    client.networkInterceptors().add(new Interceptor() {
        @Override//  www  . ja  va2 s  . c  om
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "abc");
            return chain.proceed(originalRequest.newBuilder().method("POST", body)
                    .header("Content-Type", mediaType.toString())
                    .header("Content-Length", Long.toString(body.contentLength())).build());
        }
    });

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

    client.newCall(request).execute();

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("POST", recordedRequest.getMethod());
    assertEquals("abc", recordedRequest.getBody().readUtf8());
}

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

License:Apache License

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

    interceptors.add(new Interceptor() {
        @Override// w  w w. j  a va2s  . com
        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.url("/")).addHeader("Original-Header", "foo")
            .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build();

    client.newCall(request).execute();

    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.test.InterceptorTest.java

License:Apache License

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

    interceptors.add(new Interceptor() {
        @Override/*  www  .  j a v  a2 s  .c  om*/
        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.url("/")).build();

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