Search in sources :

Example 11 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class RealConnection method connectTls.

private void connectTls(ConnectionSpecSelector connectionSpecSelector) throws IOException {
    Address address = route.address();
    SSLSocketFactory sslSocketFactory = address.sslSocketFactory();
    boolean success = false;
    SSLSocket sslSocket = null;
    try {
        // Create the wrapper over the connected socket.
        sslSocket = (SSLSocket) sslSocketFactory.createSocket(rawSocket, address.url().host(), address.url().port(), true);
        // Configure the socket's ciphers, TLS versions, and extensions.
        ConnectionSpec connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket);
        if (connectionSpec.supportsTlsExtensions()) {
            Platform.get().configureTlsExtensions(sslSocket, address.url().host(), address.protocols());
        }
        // Force handshake. This can throw!
        sslSocket.startHandshake();
        Handshake unverifiedHandshake = Handshake.get(sslSocket.getSession());
        // Verify that the socket's certificates are acceptable for the target host.
        if (!address.hostnameVerifier().verify(address.url().host(), sslSocket.getSession())) {
            X509Certificate cert = (X509Certificate) unverifiedHandshake.peerCertificates().get(0);
            throw new SSLPeerUnverifiedException("Hostname " + address.url().host() + " not verified:" + "\n    certificate: " + CertificatePinner.pin(cert) + "\n    DN: " + cert.getSubjectDN().getName() + "\n    subjectAltNames: " + OkHostnameVerifier.allSubjectAltNames(cert));
        }
        // Check that the certificate pinner is satisfied by the certificates presented.
        address.certificatePinner().check(address.url().host(), unverifiedHandshake.peerCertificates());
        // Success! Save the handshake and the ALPN protocol.
        String maybeProtocol = connectionSpec.supportsTlsExtensions() ? Platform.get().getSelectedProtocol(sslSocket) : null;
        socket = sslSocket;
        source = Okio.buffer(Okio.source(socket));
        sink = Okio.buffer(Okio.sink(socket));
        handshake = unverifiedHandshake;
        protocol = maybeProtocol != null ? Protocol.get(maybeProtocol) : Protocol.HTTP_1_1;
        success = true;
    } catch (AssertionError e) {
        if (Util.isAndroidGetsocknameError(e))
            throw new IOException(e);
        throw e;
    } finally {
        if (sslSocket != null) {
            Platform.get().afterHandshake(sslSocket);
        }
        if (!success) {
            closeQuietly(sslSocket);
        }
    }
}
Also used : Address(okhttp3.Address) ConnectionSpec(okhttp3.ConnectionSpec) SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) X509Certificate(java.security.cert.X509Certificate) Handshake(okhttp3.Handshake)

Example 12 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class Platform method alpnProtocolNames.

public static List<String> alpnProtocolNames(List<Protocol> protocols) {
    List<String> names = new ArrayList<>(protocols.size());
    for (int i = 0, size = protocols.size(); i < size; i++) {
        Protocol protocol = protocols.get(i);
        // No HTTP/1.0 for ALPN.
        if (protocol == Protocol.HTTP_1_0)
            continue;
        names.add(protocol.toString());
    }
    return names;
}
Also used : ArrayList(java.util.ArrayList) Protocol(okhttp3.Protocol)

Example 13 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class Http2Server method run.

private void run() throws Exception {
    ServerSocket serverSocket = new ServerSocket(8888);
    serverSocket.setReuseAddress(true);
    while (true) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            SSLSocket sslSocket = doSsl(socket);
            String protocolString = Platform.get().getSelectedProtocol(sslSocket);
            Protocol protocol = protocolString != null ? Protocol.get(protocolString) : null;
            if (protocol != Protocol.HTTP_2) {
                throw new ProtocolException("Protocol " + protocol + " unsupported");
            }
            Http2Connection connection = new Http2Connection.Builder(false).socket(sslSocket).listener(this).build();
            connection.start();
        } catch (IOException e) {
            logger.log(Level.INFO, "Http2Server connection failure: " + e);
            Util.closeQuietly(socket);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Http2Server unexpected failure", e);
            Util.closeQuietly(socket);
        }
    }
}
Also used : ProtocolException(java.net.ProtocolException) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) Protocol(okhttp3.Protocol) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException)

Example 14 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class MockWebServer method handleWebSocketUpgrade.

private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink, RecordedRequest request, MockResponse response) throws IOException {
    String key = request.getHeader("Sec-WebSocket-Key");
    response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key));
    writeHttpResponse(socket, sink, response);
    // Adapt the request and response into our Request and Response domain model.
    String scheme = request.getTlsVersion() != null ? "https" : "http";
    // Has host and port.
    String authority = request.getHeader("Host");
    final Request fancyRequest = new Request.Builder().url(scheme + "://" + authority + "/").headers(request.getHeaders()).build();
    final Response fancyResponse = new Response.Builder().code(Integer.parseInt(response.getStatus().split(" ")[1])).message(response.getStatus().split(" ", 3)[2]).headers(response.getHeaders()).request(fancyRequest).protocol(Protocol.HTTP_1_1).build();
    final CountDownLatch connectionClose = new CountDownLatch(1);
    RealWebSocket.Streams streams = new RealWebSocket.Streams(false, source, sink) {

        @Override
        public void close() {
            connectionClose.countDown();
        }
    };
    RealWebSocket webSocket = new RealWebSocket(fancyRequest, response.getWebSocketListener(), new SecureRandom());
    response.getWebSocketListener().onOpen(webSocket, fancyResponse);
    String name = "MockWebServer WebSocket " + request.getPath();
    webSocket.initReaderAndWriter(name, 0, streams);
    try {
        webSocket.loopReader();
        // Even if messages are no longer being read we need to wait for the connection close signal.
        try {
            connectionClose.await();
        } catch (InterruptedException ignored) {
        }
    } catch (IOException e) {
        webSocket.failWebSocket(e, null);
    } finally {
        closeQuietly(sink);
        closeQuietly(source);
    }
}
Also used : Response(okhttp3.Response) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Request(okhttp3.Request) SecureRandom(java.security.SecureRandom) ByteString(okio.ByteString) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 15 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class JavaApiConverterTest method createJavaUrlConnection_responseHeadersOk.

@Test
public void createJavaUrlConnection_responseHeadersOk() throws Exception {
    ResponseBody responseBody = createResponseBody("BodyText");
    Response okResponse = new Response.Builder().request(createArbitraryOkRequest()).protocol(Protocol.HTTP_1_1).code(200).message("Fantastic").addHeader("A", "c").addHeader("B", "d").addHeader("A", "e").addHeader("Content-Length", Long.toString(responseBody.contentLength())).body(responseBody).build();
    HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnectionForCachePut(okResponse);
    assertEquals(200, httpUrlConnection.getResponseCode());
    assertEquals("Fantastic", httpUrlConnection.getResponseMessage());
    assertEquals(responseBody.contentLength(), httpUrlConnection.getContentLength());
    // Check retrieval by string key.
    assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(null));
    assertEquals("e", httpUrlConnection.getHeaderField("A"));
    // The RI and OkHttp supports case-insensitive matching for this method.
    assertEquals("e", httpUrlConnection.getHeaderField("a"));
    // Check retrieval using a Map.
    Map<String, List<String>> responseHeaders = httpUrlConnection.getHeaderFields();
    assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), responseHeaders.get(null));
    assertEquals(newSet("c", "e"), newSet(responseHeaders.get("A")));
    // OkHttp supports case-insensitive matching here. The RI does not.
    assertEquals(newSet("c", "e"), newSet(responseHeaders.get("a")));
    // Check the Map iterator contains the expected mappings.
    assertHeadersContainsMapping(responseHeaders, null, "HTTP/1.1 200 Fantastic");
    assertHeadersContainsMapping(responseHeaders, "A", "c", "e");
    assertHeadersContainsMapping(responseHeaders, "B", "d");
    // Check immutability of the headers Map.
    try {
        responseHeaders.put("N", Arrays.asList("o"));
        fail("Modified an unmodifiable view.");
    } catch (UnsupportedOperationException expected) {
    }
    try {
        responseHeaders.get("A").add("f");
        fail("Modified an unmodifiable view.");
    } catch (UnsupportedOperationException expected) {
    }
    // Check retrieval of headers by index.
    assertEquals(null, httpUrlConnection.getHeaderFieldKey(0));
    assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(0));
    // After header zero there may be additional entries provided at the beginning or end by the
    // implementation. It's probably important that the relative ordering of the headers is
    // preserved, particularly if there are multiple value for the same key.
    int i = 1;
    while (!httpUrlConnection.getHeaderFieldKey(i).equals("A")) {
        i++;
    }
    // Check the ordering of the headers set by app code.
    assertResponseHeaderAtIndex(httpUrlConnection, i++, "A", "c");
    assertResponseHeaderAtIndex(httpUrlConnection, i++, "B", "d");
    assertResponseHeaderAtIndex(httpUrlConnection, i++, "A", "e");
    // There may be some additional headers provided by the implementation.
    while (httpUrlConnection.getHeaderField(i) != null) {
        assertNotNull(httpUrlConnection.getHeaderFieldKey(i));
        i++;
    }
    // Confirm the correct behavior when the index is out-of-range.
    assertNull(httpUrlConnection.getHeaderFieldKey(i));
}
Also used : CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) HttpURLConnection(java.net.HttpURLConnection) List(java.util.List) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

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