Search in sources :

Example 41 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class ResponseCacheTest method secureResponseCachingAndProtocolRedirects.

/**
   * We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal
   * to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and
   * HttpURLConnection was always HTTP; in practice redirects mean that each can do either.
   *
   * https://github.com/square/okhttp/issues/214
   */
@Test
public void secureResponseCachingAndProtocolRedirects() throws IOException {
    server2.useHttps(sslClient.socketFactory, false);
    server2.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setBody("ABC"));
    server2.enqueue(new MockResponse().setBody("DEF"));
    server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(HttpURLConnection.HTTP_MOVED_PERM).addHeader("Location: " + server2.url("/").url()));
    urlFactory.setClient(urlFactory.client().newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build());
    HttpURLConnection connection1 = openConnection(server.url("/").url());
    assertEquals("ABC", readAscii(connection1));
    // Cached!
    HttpURLConnection connection2 = openConnection(server.url("/").url());
    assertEquals("ABC", readAscii(connection2));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) Test(org.junit.Test)

Example 42 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 43 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class CallTest method interceptorGetsHttp2.

@Test
public void interceptorGetsHttp2() throws Exception {
    enableProtocol(Protocol.HTTP_2);
    // Capture the protocol as it is observed by the interceptor.
    final AtomicReference<Protocol> protocolRef = new AtomicReference<>();
    Interceptor interceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            protocolRef.set(chain.connection().protocol());
            return chain.proceed(chain.request());
        }
    };
    client = client.newBuilder().addNetworkInterceptor(interceptor).build();
    // Make an HTTP/2 request and confirm that the protocol matches.
    server.enqueue(new MockResponse());
    executeSynchronously("/");
    assertEquals(Protocol.HTTP_2, protocolRef.get());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 44 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class InterceptorTest method applicationInterceptorsCanShortCircuitResponses.

@Test
public void applicationInterceptorsCanShortCircuitResponses() throws Exception {
    // Accept no connections.
    server.shutdown();
    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 = client.newBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            return interceptorResponse;
        }
    }).build();
    Response response = client.newCall(request).execute();
    assertSame(interceptorResponse, response);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) IOException(java.io.IOException) Test(org.junit.Test)

Example 45 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class ExternalHttp2Example method main.

public static void main(String[] args) throws Exception {
    OkHttpClient client = new OkHttpClient.Builder().protocols(Util.immutableList(Protocol.HTTP_2, Protocol.HTTP_1_1)).build();
    Call call = client.newCall(new Request.Builder().url("https://www.google.ca/").build());
    Response response = call.execute();
    try {
        System.out.println(response.code());
        System.out.println("PROTOCOL " + response.protocol());
        String line;
        while ((line = response.body().source().readUtf8Line()) != null) {
            System.out.println(line);
        }
    } finally {
        response.body().close();
    }
    client.connectionPool().evictAll();
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

Aggregations

Request (okhttp3.Request)26 Response (okhttp3.Response)26 Test (org.junit.Test)25 ResponseBody (okhttp3.ResponseBody)20 IOException (java.io.IOException)18 Protocol (okhttp3.Protocol)14 Buffer (okio.Buffer)13 HttpResponse (com.facebook.buck.slb.HttpResponse)12 LazyPath (com.facebook.buck.io.LazyPath)11 RuleKey (com.facebook.buck.rules.RuleKey)11 Path (java.nio.file.Path)11 OkHttpResponseWrapper (com.facebook.buck.slb.OkHttpResponseWrapper)10 List (java.util.List)10 MediaType (okhttp3.MediaType)10 FakeProjectFilesystem (com.facebook.buck.testutil.FakeProjectFilesystem)9 HttpURLConnection (java.net.HttpURLConnection)9 MockResponse (okhttp3.mockwebserver.MockResponse)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 DataOutputStream (java.io.DataOutputStream)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7