Example usage for com.squareup.okhttp.internal Internal instance

List of usage examples for com.squareup.okhttp.internal Internal instance

Introduction

In this page you can find the example usage for com.squareup.okhttp.internal Internal instance.

Prototype

Internal instance

To view the source code for com.squareup.okhttp.internal Internal instance.

Click Source Link

Usage

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void timeoutsNotRetried() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse().setBody("unreachable!"));

    Internal.instance.setNetwork(client, new DoubleInetAddressNetwork());
    client.setReadTimeout(100, TimeUnit.MILLISECONDS);

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    try {/*w  w  w  .j a  v a 2  s  .  com*/
        // If this succeeds, too many requests were made.
        FiberOkHttpUtil.executeInFiber(client, request);
        fail();
    } catch (InterruptedIOException expected) {
    }
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void recoverWhenRetryOnConnectionFailureIsTrue() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
    server.enqueue(new MockResponse().setBody("retry success"));

    Internal.instance.setNetwork(client, new DoubleInetAddressNetwork());
    assertTrue(client.getRetryOnConnectionFailure());

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals("retry success", response.body().string());
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void noRecoverWhenRetryOnConnectionFailureIsFalse() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
    server.enqueue(new MockResponse().setBody("unreachable!"));

    Internal.instance.setNetwork(client, new DoubleInetAddressNetwork());
    client.setRetryOnConnectionFailure(false);

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    try {/*from   w  w w. j a  v  a 2 s  .  c  om*/
        // If this succeeds, too many requests were made.
        FiberOkHttpUtil.executeInFiber(client, request);
        fail();
    } catch (IOException expected) {
    }
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void recoverFromTlsHandshakeFailure() throws Exception {
    server.get().useHttps(sslContext.getSocketFactory(), false);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
    server.enqueue(new MockResponse().setBody("abc"));

    suppressTlsFallbackScsv(client);//  w ww  . j  a v a  2 s. c  om
    client.setHostnameVerifier(new RecordingHostnameVerifier());
    Internal.instance.setNetwork(client, new SingleInetAddressNetwork());

    FiberOkHttpTestUtil.executeInFiberRecorded(client, new Request.Builder().url(server.getUrl("/")).build())
            .assertBody("abc");
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void recoverFromTlsHandshakeFailure_tlsFallbackScsvEnabled() throws Exception {
    final String tlsFallbackScsv = "TLS_FALLBACK_SCSV";
    List<String> supportedCiphers = Arrays.asList(sslContext.getSocketFactory().getSupportedCipherSuites());
    if (!supportedCiphers.contains(tlsFallbackScsv)) {
        // This only works if the client socket supports TLS_FALLBACK_SCSV.
        return;//from  w ww.  j a  v a  2s .co  m
    }

    server.get().useHttps(sslContext.getSocketFactory(), false);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));

    RecordingSSLSocketFactory clientSocketFactory = new RecordingSSLSocketFactory(
            sslContext.getSocketFactory());
    client.setSslSocketFactory(clientSocketFactory);
    client.setHostnameVerifier(new RecordingHostnameVerifier());
    Internal.instance.setNetwork(client, new SingleInetAddressNetwork());

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    try {
        FiberOkHttpUtil.executeInFiber(client, request);
        fail();
    } catch (SSLHandshakeException expected) {
    }

    List<SSLSocket> clientSockets = clientSocketFactory.getSocketsCreated();
    SSLSocket firstSocket = clientSockets.get(0);
    assertFalse(Arrays.asList(firstSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv));
    SSLSocket secondSocket = clientSockets.get(1);
    assertTrue(Arrays.asList(secondSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv));
}

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void noRecoveryFromTlsHandshakeFailureWhenTlsFallbackIsDisabled() throws Exception {
    client.setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT));

    server.get().useHttps(sslContext.getSocketFactory(), false);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));

    suppressTlsFallbackScsv(client);// ww w .  j  a  v a  2 s  .co  m
    client.setHostnameVerifier(new RecordingHostnameVerifier());
    Internal.instance.setNetwork(client, new SingleInetAddressNetwork());

    Request request = new Request.Builder().url(server.getUrl("/")).build();
    try {
        FiberOkHttpUtil.executeInFiber(client, request);
        fail();
    } catch (SSLProtocolException expected) {
        // RI response to the FAIL_HANDSHAKE
    } catch (SSLHandshakeException expected) {
        // Android's response to the FAIL_HANDSHAKE
    }
}

From source file:com.android.mms.service_alt.MmsHttpClient.java

License:Apache License

/**
 * Open an HTTP connection/* ww w . j  a  v a  2 s . c  o m*/
 *
 * TODO: The following code is borrowed from android.net.Network.openConnection
 * Once that method supports proxy, we should use that instead
 * Also we should remove the associated HostResolver and ConnectionPool from
 * MmsNetworkManager
 *
 * @param url The URL to connect to
 * @param proxy The proxy to use
 * @return The opened HttpURLConnection
 * @throws MalformedURLException If URL is malformed
 */
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
    final String protocol = url.getProtocol();
    OkHttpClient okHttpClient;
    if (protocol.equals("http")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (proxy != null) {
                    return Arrays.asList(proxy);
                } else {
                    return new ArrayList<Proxy>();
                }
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        okHttpClient.setSocketFactory(SocketFactory.getDefault());
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        if (proxy != null) {
            okHttpClient.setProxy(proxy);
        }

        return new HttpURLConnectionImpl(url, okHttpClient);
    } else if (protocol.equals("https")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        okHttpClient.setHostnameVerifier(verifier);
        okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        return new HttpsURLConnectionImpl(url, okHttpClient);
    } else {
        throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
    }
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Constructor.//from www  .  j  a  v a  2  s  .  c om
 * @param metricsServer
 */
public HawkularMetricsClient(URL metricsServer) {
    this.serverUrl = metricsServer;
    httpClient = new OkHttpClient();
    httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setFollowRedirects(true);
    httpClient.setFollowSslRedirects(true);
    httpClient.setProxySelector(ProxySelector.getDefault());
    httpClient.setCookieHandler(CookieHandler.getDefault());
    httpClient.setCertificatePinner(CertificatePinner.DEFAULT);
    httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE);
    httpClient.setConnectionPool(ConnectionPool.getDefault());
    httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
    httpClient.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
    httpClient.setSocketFactory(SocketFactory.getDefault());
    Internal.instance.setNetwork(httpClient, Network.DEFAULT);
}

From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java

License:Apache License

/**
 * @return a new http client/*from   w  w w  .  j av a 2  s. com*/
 */
private OkHttpClient createHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS);
    client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS);
    client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS);
    client.setFollowRedirects(connectorOptions.isFollowRedirects());
    client.setFollowSslRedirects(connectorOptions.isFollowRedirects());
    client.setProxySelector(ProxySelector.getDefault());
    client.setCookieHandler(CookieHandler.getDefault());
    client.setCertificatePinner(CertificatePinner.DEFAULT);
    client.setAuthenticator(AuthenticatorAdapter.INSTANCE);
    client.setConnectionPool(ConnectionPool.getDefault());
    client.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
    client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
    client.setSocketFactory(SocketFactory.getDefault());
    Internal.instance.setNetwork(client, Network.DEFAULT);

    return client;
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ok.HttpURLConnectionImpl.java

License:Apache License

private HttpEngine newHttpEngine(String method, Connection connection, RetryableSink requestBody,
        Response priorResponse) {
    // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
    RequestBody placeholderBody = HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null;
    Request.Builder builder = new Request.Builder().url(getURL()).method(method, placeholderBody);
    Headers headers = requestHeaders.build();
    for (int i = 0, size = headers.size(); i < size; i++) {
        builder.addHeader(headers.name(i), headers.value(i));
    }/*w w  w. j  a va  2 s .  c o  m*/

    boolean bufferRequestBody = false;
    if (HttpMethod.permitsRequestBody(method)) {
        // Specify how the request body is terminated.
        if (fixedContentLength != -1) {
            builder.header("Content-Length", Long.toString(fixedContentLength));
        } else if (chunkLength > 0) {
            builder.header("Transfer-Encoding", "chunked");
        } else {
            bufferRequestBody = true;
        }

        // Add a content type for the request body, if one isn't already present.
        if (headers.get("Content-Type") == null) {
            builder.header("Content-Type", "application/x-www-form-urlencoded");
        }
    }

    if (headers.get("User-Agent") == null) {
        builder.header("User-Agent", defaultUserAgent());
    }

    Request request = builder.build();

    // If we're currently not using caches, make sure the engine's client doesn't have one.
    OkHttpClient engineClient = client;
    if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) {
        engineClient = client.clone().setCache(null);
    }

    return new HttpEngine(engineClient, request, bufferRequestBody, true, false, connection, null, requestBody,
            priorResponse);
}