Search in sources :

Example 11 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class CacheAdapterTest method put_httpPost.

@Test
public void put_httpPost() throws Exception {
    final String statusLine = "HTTP/1.1 200 Fantastic";
    final URL serverUrl = configureServer(new MockResponse().setStatus(statusLine).addHeader("A", "c"));
    ResponseCache responseCache = new AbstractResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            try {
                assertTrue(connection instanceof HttpURLConnection);
                assertFalse(connection instanceof HttpsURLConnection);
                assertEquals(0, connection.getContentLength());
                HttpURLConnection httpUrlConnection = (HttpURLConnection) connection;
                assertEquals("POST", httpUrlConnection.getRequestMethod());
                assertTrue(httpUrlConnection.getDoInput());
                assertTrue(httpUrlConnection.getDoOutput());
                assertEquals("Fantastic", httpUrlConnection.getResponseMessage());
                assertEquals(toUri(serverUrl), uri);
                assertEquals(serverUrl, connection.getURL());
                assertEquals("value", connection.getRequestProperty("key"));
                // Check retrieval by string key.
                assertEquals(statusLine, httpUrlConnection.getHeaderField(null));
                assertEquals("c", httpUrlConnection.getHeaderField("A"));
                // The RI and OkHttp supports case-insensitive matching for this method.
                assertEquals("c", httpUrlConnection.getHeaderField("a"));
                return null;
            } catch (Throwable t) {
                throw new IOException("unexpected cache failure", t);
            }
        }
    };
    setInternalCache(new CacheAdapter(responseCache));
    connection = new OkUrlFactory(client).open(serverUrl);
    executePost(connection);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) AbstractResponseCache(okhttp3.AbstractResponseCache) OkUrlFactory(okhttp3.OkUrlFactory) HttpURLConnection(java.net.HttpURLConnection) ResponseCache(java.net.ResponseCache) AbstractResponseCache(okhttp3.AbstractResponseCache) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 12 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class CacheAdapterTest method put_httpGet.

@Test
public void put_httpGet() throws Exception {
    final String statusLine = "HTTP/1.1 200 Fantastic";
    final byte[] response = "ResponseString".getBytes(StandardCharsets.UTF_8);
    final URL serverUrl = configureServer(new MockResponse().setStatus(statusLine).addHeader("A", "c").setBody(new Buffer().write(response)));
    ResponseCache responseCache = new AbstractResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            try {
                assertTrue(connection instanceof HttpURLConnection);
                assertFalse(connection instanceof HttpsURLConnection);
                assertEquals(response.length, connection.getContentLength());
                HttpURLConnection httpUrlConnection = (HttpURLConnection) connection;
                assertEquals("GET", httpUrlConnection.getRequestMethod());
                assertTrue(httpUrlConnection.getDoInput());
                assertFalse(httpUrlConnection.getDoOutput());
                assertEquals("Fantastic", httpUrlConnection.getResponseMessage());
                assertEquals(toUri(serverUrl), uri);
                assertEquals(serverUrl, connection.getURL());
                assertEquals("value", connection.getRequestProperty("key"));
                // Check retrieval by string key.
                assertEquals(statusLine, httpUrlConnection.getHeaderField(null));
                assertEquals("c", httpUrlConnection.getHeaderField("A"));
                // The RI and OkHttp supports case-insensitive matching for this method.
                assertEquals("c", httpUrlConnection.getHeaderField("a"));
                return null;
            } catch (Throwable t) {
                throw new IOException("unexpected cache failure", t);
            }
        }
    };
    setInternalCache(new CacheAdapter(responseCache));
    connection = new OkUrlFactory(client).open(serverUrl);
    connection.setRequestProperty("key", "value");
    executeGet(connection);
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) AbstractResponseCache(okhttp3.AbstractResponseCache) OkUrlFactory(okhttp3.OkUrlFactory) HttpURLConnection(java.net.HttpURLConnection) ResponseCache(java.net.ResponseCache) AbstractResponseCache(okhttp3.AbstractResponseCache) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 13 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class CacheAdapter method put.

@Override
public CacheRequest put(Response response) throws IOException {
    URI uri = response.request().url().uri();
    HttpURLConnection connection = JavaApiConverter.createJavaUrlConnectionForCachePut(response);
    final java.net.CacheRequest request = delegate.put(uri, connection);
    if (request == null) {
        return null;
    }
    return new CacheRequest() {

        @Override
        public Sink body() throws IOException {
            OutputStream body = request.getBody();
            return body != null ? Okio.sink(body) : null;
        }

        @Override
        public void abort() {
            request.abort();
        }
    };
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheRequest(okhttp3.internal.cache.CacheRequest) OutputStream(java.io.OutputStream) URI(java.net.URI)

Example 14 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class ResponseCacheTest method responseCacheCallbackApis.

// Android-added tests.
/**
   * Test that we can interrogate the response when the cache is being populated.
   * http://code.google.com/p/android/issues/detail?id=7787
   */
@Test
public void responseCacheCallbackApis() throws Exception {
    final String body = "ABCDE";
    final AtomicInteger cacheCount = new AtomicInteger();
    server.enqueue(new MockResponse().setStatus("HTTP/1.1 200 Fantastic").addHeader("Content-Type: text/plain").addHeader("fgh: ijk").setBody(body));
    setInternalCache(new CacheAdapter(new AbstractResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            assertEquals(server.url("/").url(), uri.toURL());
            assertEquals(200, httpURLConnection.getResponseCode());
            InputStream is = httpURLConnection.getInputStream();
            try {
                is.read();
                fail();
            } catch (UnsupportedOperationException expected) {
            }
            assertEquals("5", connection.getHeaderField("Content-Length"));
            assertEquals("text/plain", connection.getHeaderField("Content-Type"));
            assertEquals("ijk", connection.getHeaderField("fgh"));
            cacheCount.incrementAndGet();
            return null;
        }
    }));
    URL url = server.url("/").url();
    HttpURLConnection connection = openConnection(url);
    assertEquals(body, readAscii(connection));
    assertEquals(1, cacheCount.get());
}
Also used : AbstractResponseCache(okhttp3.AbstractResponseCache) MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URI(java.net.URI) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URL(java.net.URL) Test(org.junit.Test)

Example 15 with CacheRequest

use of okhttp3.internal.cache.CacheRequest in project okhttp by square.

the class CacheInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Response cacheCandidate = cache != null ? cache.get(chain.request()) : null;
    long now = System.currentTimeMillis();
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    if (cache != null) {
        cache.trackResponse(strategy);
    }
    if (cacheCandidate != null && cacheResponse == null) {
        // The cache candidate wasn't applicable. Close it.
        closeQuietly(cacheCandidate.body());
    }
    // If we're forbidden from using the network and the cache is insufficient, fail.
    if (networkRequest == null && cacheResponse == null) {
        return new Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(504).message("Unsatisfiable Request (only-if-cached)").body(Util.EMPTY_RESPONSE).sentRequestAtMillis(-1L).receivedResponseAtMillis(System.currentTimeMillis()).build();
    }
    // If we don't need the network, we're done.
    if (networkRequest == null) {
        return cacheResponse.newBuilder().cacheResponse(stripBody(cacheResponse)).build();
    }
    Response networkResponse = null;
    try {
        networkResponse = chain.proceed(networkRequest);
    } finally {
        // If we're crashing on I/O or otherwise, don't leak the cache body.
        if (networkResponse == null && cacheCandidate != null) {
            closeQuietly(cacheCandidate.body());
        }
    }
    // If we have a cache response too, then we're doing a conditional get.
    if (cacheResponse != null) {
        if (networkResponse.code() == HTTP_NOT_MODIFIED) {
            Response response = cacheResponse.newBuilder().headers(combine(cacheResponse.headers(), networkResponse.headers())).sentRequestAtMillis(networkResponse.sentRequestAtMillis()).receivedResponseAtMillis(networkResponse.receivedResponseAtMillis()).cacheResponse(stripBody(cacheResponse)).networkResponse(stripBody(networkResponse)).build();
            networkResponse.body().close();
            // Update the cache after combining headers but before stripping the
            // Content-Encoding header (as performed by initContentStream()).
            cache.trackConditionalCacheHit();
            cache.update(cacheResponse, response);
            return response;
        } else {
            closeQuietly(cacheResponse.body());
        }
    }
    Response response = networkResponse.newBuilder().cacheResponse(stripBody(cacheResponse)).networkResponse(stripBody(networkResponse)).build();
    if (HttpHeaders.hasBody(response)) {
        CacheRequest cacheRequest = maybeCache(response, networkResponse.request(), cache);
        response = cacheWritingResponse(cacheRequest, response);
    }
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

Aggregations

URI (java.net.URI)9 IOException (java.io.IOException)7 HttpURLConnection (java.net.HttpURLConnection)7 Request (okhttp3.Request)7 Test (org.junit.Test)7 URLConnection (java.net.URLConnection)5 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)5 AbstractResponseCache (okhttp3.AbstractResponseCache)5 Response (okhttp3.Response)5 MockResponse (okhttp3.mockwebserver.MockResponse)5 URL (java.net.URL)4 OkUrlFactory (okhttp3.OkUrlFactory)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 CacheResponse (java.net.CacheResponse)3 ResponseCache (java.net.ResponseCache)3 SecureCacheResponse (java.net.SecureCacheResponse)3 Headers (okhttp3.Headers)3 CacheRequest (okhttp3.internal.cache.CacheRequest)3 ArtifactMetadata (com.facebook.buck.artifact_cache.thrift.ArtifactMetadata)2 BuckCacheFetchRequest (com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest)2