Search in sources :

Example 61 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class InterceptorTest method interceptorMakesAnUnrelatedAsyncRequest.

/** Make sure interceptors can interact with the OkHttp client asynchronously. */
@Test
public void interceptorMakesAnUnrelatedAsyncRequest() throws Exception {
    // Fetched by interceptor.
    server.enqueue(new MockResponse().setBody("a"));
    // Fetched directly.
    server.enqueue(new MockResponse().setBody("b"));
    client = client.newBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain.request().url().encodedPath().equals("/b")) {
                Request requestA = new Request.Builder().url(server.url("/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());
        }
    }).build();
    Request requestB = new Request.Builder().url(server.url("/b")).build();
    RecordingCallback callbackB = new RecordingCallback();
    client.newCall(requestB).enqueue(callbackB);
    callbackB.await(requestB.url()).assertBody("b");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) IOException(java.io.IOException) IOException(java.io.IOException) Test(org.junit.Test)

Example 62 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class InterceptorTest method networkInterceptorsObserveNetworkHeaders.

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

        @Override
        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;
        }
    };
    client = client.newBuilder().addNetworkInterceptor(interceptor).build();
    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());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 63 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class InterceptorTest method interceptorMakesAnUnrelatedRequest.

/** Make sure interceptors can interact with the OkHttp client. */
@Test
public void interceptorMakesAnUnrelatedRequest() throws Exception {
    // Fetched by interceptor.
    server.enqueue(new MockResponse().setBody("a"));
    // Fetched directly.
    server.enqueue(new MockResponse().setBody("b"));
    client = client.newBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain.request().url().encodedPath().equals("/b")) {
                Request requestA = new Request.Builder().url(server.url("/a")).build();
                Response responseA = client.newCall(requestA).execute();
                assertEquals("a", responseA.body().string());
            }
            return chain.proceed(chain.request());
        }
    }).build();
    Request requestB = new Request.Builder().url(server.url("/b")).build();
    Response responseB = client.newCall(requestB).execute();
    assertEquals("b", responseB.body().string());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) IOException(java.io.IOException) Test(org.junit.Test)

Example 64 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class HttpOverHttp2Test method connectionShutdownAfterHealthCheck.

/**
   * This simulates a race condition where we receive a healthy HTTP/2 connection and just prior to
   * writing our request, we get a GOAWAY frame from the server.
   */
@Test
public void connectionShutdownAfterHealthCheck() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_END).setBody("ABC"));
    server.enqueue(new MockResponse().setBody("DEF"));
    OkHttpClient client2 = client.newBuilder().addNetworkInterceptor(new Interceptor() {

        boolean executedCall;

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (!executedCall) {
                // At this point, we have a healthy HTTP/2 connection. This call will trigger the
                // server to send a GOAWAY frame, leaving the connection in a shutdown state.
                executedCall = true;
                Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
                Response response = call.execute();
                assertEquals("ABC", response.body().string());
                // Wait until the GOAWAY has been processed.
                RealConnection connection = (RealConnection) chain.connection();
                while (connection.isHealthy(false)) ;
            }
            return chain.proceed(chain.request());
        }
    }).build();
    Call call = client2.newCall(new Request.Builder().url(server.url("/")).build());
    Response response = call.execute();
    assertEquals("DEF", response.body().string());
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(0, server.takeRequest().getSequenceNumber());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) RealConnection(okhttp3.internal.connection.RealConnection) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 65 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class RealInterceptorChain method proceed.

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException {
    if (index >= interceptors.size())
        throw new AssertionError();
    calls++;
    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
        throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must retain the same host and port");
    }
    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpCodec != null && calls > 1) {
        throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once");
    }
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
        throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once");
    }
    // Confirm that the intercepted response isn't null.
    if (response == null) {
        throw new NullPointerException("interceptor " + interceptor + " returned null");
    }
    return response;
}
Also used : Response(okhttp3.Response) Interceptor(okhttp3.Interceptor)

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