Search in sources :

Example 41 with Headers

use of okhttp3.Headers in project okhttp by square.

the class JavaApiConverterTest method createOkResponseForCacheGet.

@Test
public void createOkResponseForCacheGet() throws Exception {
    final String statusLine = "HTTP/1.1 200 Fantastic";
    URI uri = new URI("http://foo/bar");
    Request request = new Request.Builder().url(uri.toURL()).build();
    CacheResponse cacheResponse = new CacheResponse() {

        @Override
        public Map<String, List<String>> getHeaders() throws IOException {
            Map<String, List<String>> headers = new LinkedHashMap<>();
            headers.put(null, Collections.singletonList(statusLine));
            headers.put("xyzzy", Arrays.asList("bar", "baz"));
            return headers;
        }

        @Override
        public InputStream getBody() throws IOException {
            return new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8));
        }
    };
    Response response = JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
    Request cacheRequest = response.request();
    assertEquals(request.url(), cacheRequest.url());
    assertEquals(request.method(), cacheRequest.method());
    assertEquals(0, request.headers().size());
    assertEquals(Protocol.HTTP_1_1, response.protocol());
    assertEquals(200, response.code());
    assertEquals("Fantastic", response.message());
    Headers okResponseHeaders = response.headers();
    assertEquals("baz", okResponseHeaders.get("xyzzy"));
    assertEquals("HelloWorld", response.body().string());
    assertNull(response.handshake());
}
Also used : CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) CacheResponse(java.net.CacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Headers(okhttp3.Headers) Request(okhttp3.Request) List(java.util.List) URI(java.net.URI) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 42 with Headers

use of okhttp3.Headers in project okhttp by square.

the class ResponseCacheTest method assertConditionallyCached.

/** @return the request with the conditional get headers. */
private RecordedRequest assertConditionallyCached(MockResponse response) throws Exception {
    // scenario 1: condition succeeds
    server.enqueue(response.setBody("A").setStatus("HTTP/1.1 200 A-OK"));
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    // scenario 2: condition fails
    server.enqueue(response.setBody("B").setStatus("HTTP/1.1 200 B-OK"));
    server.enqueue(new MockResponse().setStatus("HTTP/1.1 200 C-OK").setBody("C"));
    URL valid = server.url("/valid").url();
    HttpURLConnection connection1 = openConnection(valid);
    assertEquals("A", readAscii(connection1));
    assertEquals(HttpURLConnection.HTTP_OK, connection1.getResponseCode());
    assertEquals("A-OK", connection1.getResponseMessage());
    HttpURLConnection connection2 = openConnection(valid);
    assertEquals("A", readAscii(connection2));
    assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
    assertEquals("A-OK", connection2.getResponseMessage());
    URL invalid = server.url("/invalid").url();
    HttpURLConnection connection3 = openConnection(invalid);
    assertEquals("B", readAscii(connection3));
    assertEquals(HttpURLConnection.HTTP_OK, connection3.getResponseCode());
    assertEquals("B-OK", connection3.getResponseMessage());
    HttpURLConnection connection4 = openConnection(invalid);
    assertEquals("C", readAscii(connection4));
    assertEquals(HttpURLConnection.HTTP_OK, connection4.getResponseCode());
    assertEquals("C-OK", connection4.getResponseMessage());
    // regular get
    server.takeRequest();
    // conditional get
    return server.takeRequest();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Example 43 with Headers

use of okhttp3.Headers in project okhttp by square.

the class ResponseCacheTest method otherStacks_cacheMissWithVaryAsterisk.

// Other stacks (e.g. older versions of OkHttp bundled inside Android apps) can interact with the
// default ResponseCache. We can't keep the Vary case working, because we can't get to the Vary
// request headers after connect().
@Test
public void otherStacks_cacheMissWithVaryAsterisk() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: *").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    // Set the cache as the shared cache.
    ResponseCache.setDefault(cache);
    // Use the platform's HTTP stack.
    URLConnection connection = server.url("/").url().openConnection();
    assertFalse(connection instanceof OkHttpURLConnection);
    assertEquals("A", readAscii(connection));
    URLConnection connection2 = server.url("/").url().openConnection();
    assertFalse(connection2 instanceof OkHttpURLConnection);
    assertEquals("B", readAscii(connection2));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 44 with Headers

use of okhttp3.Headers in project okhttp by square.

the class JavaApiConverter method createOkResponseForCacheGet.

/**
   * Creates an OkHttp {@link Response} using the supplied {@link Request} and {@link CacheResponse}
   * to supply the data.
   */
static Response createOkResponseForCacheGet(Request request, CacheResponse javaResponse) throws IOException {
    // Build a cache request for the response to use.
    Headers responseHeaders = createHeaders(javaResponse.getHeaders());
    Headers varyHeaders;
    if (HttpHeaders.hasVaryAll(responseHeaders)) {
        // "*" means that this will be treated as uncacheable anyway.
        varyHeaders = new Headers.Builder().build();
    } else {
        varyHeaders = HttpHeaders.varyHeaders(request.headers(), responseHeaders);
    }
    Request cacheRequest = new Request.Builder().url(request.url()).method(request.method(), null).headers(varyHeaders).build();
    Response.Builder okResponseBuilder = new Response.Builder();
    // Request: Use the cacheRequest we built.
    okResponseBuilder.request(cacheRequest);
    // Status line: Java has this as one of the headers.
    StatusLine statusLine = StatusLine.parse(extractStatusLine(javaResponse));
    okResponseBuilder.protocol(statusLine.protocol);
    okResponseBuilder.code(statusLine.code);
    okResponseBuilder.message(statusLine.message);
    // Response headers
    Headers okHeaders = extractOkHeaders(javaResponse, okResponseBuilder);
    okResponseBuilder.headers(okHeaders);
    // Response body
    ResponseBody okBody = createOkBody(okHeaders, javaResponse);
    okResponseBuilder.body(okBody);
    // Handle SSL handshake information as needed.
    if (javaResponse instanceof SecureCacheResponse) {
        SecureCacheResponse javaSecureCacheResponse = (SecureCacheResponse) javaResponse;
        // Handshake doesn't support null lists.
        List<Certificate> peerCertificates;
        try {
            peerCertificates = javaSecureCacheResponse.getServerCertificateChain();
        } catch (SSLPeerUnverifiedException e) {
            peerCertificates = Collections.emptyList();
        }
        List<Certificate> localCertificates = javaSecureCacheResponse.getLocalCertificateChain();
        if (localCertificates == null) {
            localCertificates = Collections.emptyList();
        }
        String cipherSuiteString = javaSecureCacheResponse.getCipherSuite();
        CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
        Handshake handshake = Handshake.get(null, cipherSuite, peerCertificates, localCertificates);
        okResponseBuilder.handshake(handshake);
    }
    return okResponseBuilder.build();
}
Also used : SecureCacheResponse(java.net.SecureCacheResponse) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) JavaNetHeaders(okhttp3.internal.JavaNetHeaders) CipherSuite(okhttp3.CipherSuite) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CacheRequest(okhttp3.internal.cache.CacheRequest) Request(okhttp3.Request) ResponseBody(okhttp3.ResponseBody) CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) StatusLine(okhttp3.internal.http.StatusLine) Certificate(java.security.cert.Certificate) Handshake(okhttp3.Handshake)

Example 45 with Headers

use of okhttp3.Headers in project okhttp by square.

the class JavaApiConverter method createJavaCacheResponse.

/**
   * Creates a {@link java.net.CacheResponse} of the correct (sub)type using information gathered
   * from the supplied {@link Response}.
   */
public static CacheResponse createJavaCacheResponse(final Response response) {
    final Headers headers = withSyntheticHeaders(response);
    final ResponseBody body = response.body();
    if (response.request().isHttps()) {
        final Handshake handshake = response.handshake();
        return new SecureCacheResponse() {

            @Override
            public String getCipherSuite() {
                return handshake != null ? handshake.cipherSuite().javaName() : null;
            }

            @Override
            public List<Certificate> getLocalCertificateChain() {
                if (handshake == null)
                    return null;
                // Java requires null, not an empty list here.
                List<Certificate> certificates = handshake.localCertificates();
                return certificates.size() > 0 ? certificates : null;
            }

            @Override
            public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
                if (handshake == null)
                    return null;
                // Java requires null, not an empty list here.
                List<Certificate> certificates = handshake.peerCertificates();
                return certificates.size() > 0 ? certificates : null;
            }

            @Override
            public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
                if (handshake == null)
                    return null;
                return handshake.peerPrincipal();
            }

            @Override
            public Principal getLocalPrincipal() {
                if (handshake == null)
                    return null;
                return handshake.localPrincipal();
            }

            @Override
            public Map<String, List<String>> getHeaders() throws IOException {
                // Java requires that the entry with a null key be the status line.
                return JavaNetHeaders.toMultimap(headers, StatusLine.get(response).toString());
            }

            @Override
            public InputStream getBody() throws IOException {
                if (body == null)
                    return null;
                return body.byteStream();
            }
        };
    } else {
        return new CacheResponse() {

            @Override
            public Map<String, List<String>> getHeaders() throws IOException {
                // Java requires that the entry with a null key be the status line.
                return JavaNetHeaders.toMultimap(headers, StatusLine.get(response).toString());
            }

            @Override
            public InputStream getBody() throws IOException {
                if (body == null)
                    return null;
                return body.byteStream();
            }
        };
    }
}
Also used : CacheResponse(java.net.CacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) JavaNetHeaders(okhttp3.internal.JavaNetHeaders) List(java.util.List) ResponseBody(okhttp3.ResponseBody) Handshake(okhttp3.Handshake) Certificate(java.security.cert.Certificate)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)58 Response (okhttp3.Response)53 Headers (okhttp3.Headers)46 IOException (java.io.IOException)34 MockResponse (okhttp3.mockwebserver.MockResponse)33 HttpHeaders (okhttp3.internal.http.HttpHeaders)29 ResponseBody (okhttp3.ResponseBody)27 RequestBody (okhttp3.RequestBody)21 List (java.util.List)19 MediaType (okhttp3.MediaType)16 HashMap (java.util.HashMap)15 Map (java.util.Map)15 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Buffer (okio.Buffer)12 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11