Search in sources :

Example 6 with StatusLine

use of okhttp3.internal.http.StatusLine 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 7 with StatusLine

use of okhttp3.internal.http.StatusLine in project okhttp by square.

the class JavaApiConverter method createOkResponseForCachePut.

/**
   * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to
   * supply the data. The URLConnection is assumed to already be connected. If this method returns
   * {@code null} the response is uncacheable.
   */
public static Response createOkResponseForCachePut(URI uri, URLConnection urlConnection) throws IOException {
    HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
    Response.Builder okResponseBuilder = new Response.Builder();
    // Request: Create one from the URL connection.
    Headers responseHeaders = createHeaders(urlConnection.getHeaderFields());
    // Some request headers are needed for Vary caching.
    Headers varyHeaders = varyHeaders(urlConnection, responseHeaders);
    if (varyHeaders == null) {
        return null;
    }
    // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
    String requestMethod = httpUrlConnection.getRequestMethod();
    RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod) ? Util.EMPTY_REQUEST : null;
    Request okRequest = new Request.Builder().url(uri.toString()).method(requestMethod, placeholderBody).headers(varyHeaders).build();
    okResponseBuilder.request(okRequest);
    // Status line
    StatusLine statusLine = StatusLine.parse(extractStatusLine(httpUrlConnection));
    okResponseBuilder.protocol(statusLine.protocol);
    okResponseBuilder.code(statusLine.code);
    okResponseBuilder.message(statusLine.message);
    // A network response is required for the Cache to find any Vary headers it needs.
    Response networkResponse = okResponseBuilder.build();
    okResponseBuilder.networkResponse(networkResponse);
    // Response headers
    Headers okHeaders = extractOkResponseHeaders(httpUrlConnection, okResponseBuilder);
    okResponseBuilder.headers(okHeaders);
    // Response body
    ResponseBody okBody = createOkBody(urlConnection);
    okResponseBuilder.body(okBody);
    // Handle SSL handshake information as needed.
    if (httpUrlConnection instanceof HttpsURLConnection) {
        HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) httpUrlConnection;
        Certificate[] peerCertificates;
        try {
            peerCertificates = httpsUrlConnection.getServerCertificates();
        } catch (SSLPeerUnverifiedException e) {
            peerCertificates = null;
        }
        Certificate[] localCertificates = httpsUrlConnection.getLocalCertificates();
        String cipherSuiteString = httpsUrlConnection.getCipherSuite();
        CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
        Handshake handshake = Handshake.get(null, cipherSuite, nullSafeImmutableList(peerCertificates), nullSafeImmutableList(localCertificates));
        okResponseBuilder.handshake(handshake);
    }
    return okResponseBuilder.build();
}
Also used : 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) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) RequestBody(okhttp3.RequestBody) Certificate(java.security.cert.Certificate) Handshake(okhttp3.Handshake)

Example 8 with StatusLine

use of okhttp3.internal.http.StatusLine in project okhttp by square.

the class JavaApiConverterTest method extractOkHeaders.

@Test
public void extractOkHeaders() {
    Map<String, List<String>> javaResponseHeaders = new LinkedHashMap<>();
    javaResponseHeaders.put(null, Arrays.asList("StatusLine"));
    javaResponseHeaders.put("key1", Arrays.asList("value1_1", "value1_2"));
    javaResponseHeaders.put("key2", Arrays.asList("value2"));
    Headers okHeaders = JavaApiConverter.extractOkHeaders(javaResponseHeaders, null);
    // null entry should be stripped out
    assertEquals(3, okHeaders.size());
    assertEquals(Arrays.asList("value1_1", "value1_2"), okHeaders.values("key1"));
    assertEquals(Arrays.asList("value2"), okHeaders.values("key2"));
}
Also used : Headers(okhttp3.Headers) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 9 with StatusLine

use of okhttp3.internal.http.StatusLine in project okhttp by square.

the class Http2Codec method readHttp2HeadersList.

/** Returns headers for a name value block containing an HTTP/2 response. */
public static Response.Builder readHttp2HeadersList(List<Header> headerBlock) throws IOException {
    StatusLine statusLine = null;
    Headers.Builder headersBuilder = new Headers.Builder();
    for (int i = 0, size = headerBlock.size(); i < size; i++) {
        Header header = headerBlock.get(i);
        // header blocks if the existing header block is a '100 Continue' intermediate response.
        if (header == null) {
            if (statusLine != null && statusLine.code == HTTP_CONTINUE) {
                statusLine = null;
                headersBuilder = new Headers.Builder();
            }
            continue;
        }
        ByteString name = header.name;
        String value = header.value.utf8();
        if (name.equals(RESPONSE_STATUS)) {
            statusLine = StatusLine.parse("HTTP/1.1 " + value);
        } else if (!HTTP_2_SKIPPED_RESPONSE_HEADERS.contains(name)) {
            Internal.instance.addLenient(headersBuilder, name.utf8(), value);
        }
    }
    if (statusLine == null)
        throw new ProtocolException("Expected ':status' header not present");
    return new Response.Builder().protocol(Protocol.HTTP_2).code(statusLine.code).message(statusLine.message).headers(headersBuilder.build());
}
Also used : StatusLine(okhttp3.internal.http.StatusLine) ProtocolException(java.net.ProtocolException) Headers(okhttp3.Headers) ByteString(okio.ByteString) ByteString(okio.ByteString)

Example 10 with StatusLine

use of okhttp3.internal.http.StatusLine in project okhttp by square.

the class StatusLine method parse.

public static StatusLine parse(String statusLine) throws IOException {
    // H T T P / 1 . 1   2 0 0   T e m p o r a r y   R e d i r e c t
    // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
    // Parse protocol like "HTTP/1.1" followed by a space.
    int codeStart;
    Protocol protocol;
    if (statusLine.startsWith("HTTP/1.")) {
        if (statusLine.length() < 9 || statusLine.charAt(8) != ' ') {
            throw new ProtocolException("Unexpected status line: " + statusLine);
        }
        int httpMinorVersion = statusLine.charAt(7) - '0';
        codeStart = 9;
        if (httpMinorVersion == 0) {
            protocol = Protocol.HTTP_1_0;
        } else if (httpMinorVersion == 1) {
            protocol = Protocol.HTTP_1_1;
        } else {
            throw new ProtocolException("Unexpected status line: " + statusLine);
        }
    } else if (statusLine.startsWith("ICY ")) {
        // Shoutcast uses ICY instead of "HTTP/1.0".
        protocol = Protocol.HTTP_1_0;
        codeStart = 4;
    } else {
        throw new ProtocolException("Unexpected status line: " + statusLine);
    }
    // Parse response code like "200". Always 3 digits.
    if (statusLine.length() < codeStart + 3) {
        throw new ProtocolException("Unexpected status line: " + statusLine);
    }
    int code;
    try {
        code = Integer.parseInt(statusLine.substring(codeStart, codeStart + 3));
    } catch (NumberFormatException e) {
        throw new ProtocolException("Unexpected status line: " + statusLine);
    }
    // Parse an optional response message like "OK" or "Not Modified". If it
    // exists, it is separated from the response code by a space.
    String message = "";
    if (statusLine.length() > codeStart + 3) {
        if (statusLine.charAt(codeStart + 3) != ' ') {
            throw new ProtocolException("Unexpected status line: " + statusLine);
        }
        message = statusLine.substring(codeStart + 4);
    }
    return new StatusLine(protocol, code, message);
}
Also used : ProtocolException(java.net.ProtocolException) Protocol(okhttp3.Protocol)

Aggregations

Headers (okhttp3.Headers)6 Response (okhttp3.Response)5 StatusLine (okhttp3.internal.http.StatusLine)5 Test (org.junit.Test)5 CacheResponse (java.net.CacheResponse)4 SecureCacheResponse (java.net.SecureCacheResponse)4 URI (java.net.URI)4 Request (okhttp3.Request)4 IOException (java.io.IOException)3 HttpURLConnection (java.net.HttpURLConnection)3 Certificate (java.security.cert.Certificate)3 LinkedHashMap (java.util.LinkedHashMap)3 List (java.util.List)3 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)3 Handshake (okhttp3.Handshake)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ProtocolException (java.net.ProtocolException)2 ResponseCache (java.net.ResponseCache)2 URL (java.net.URL)2 URLConnection (java.net.URLConnection)2