Example usage for com.squareup.okhttp ConnectionSpec CLEARTEXT

List of usage examples for com.squareup.okhttp ConnectionSpec CLEARTEXT

Introduction

In this page you can find the example usage for com.squareup.okhttp ConnectionSpec CLEARTEXT.

Prototype

ConnectionSpec CLEARTEXT

To view the source code for com.squareup.okhttp ConnectionSpec CLEARTEXT.

Click Source Link

Document

Unencrypted, unauthenticated connections for http: URLs.

Usage

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);/*from w ww .ja  v  a 2  s . c  om*/
    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//from   ww  w  .  j  a  v a 2s .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:com.cloudant.http.internal.ok.OkHttpClientHttpUrlConnectionFactory.java

License:Open Source License

public OkHttpClientHttpUrlConnectionFactory() {
    client = new OkHttpClient();
    client.setConnectionSpecs(Arrays.asList(new ConnectionSpec[] { ConnectionSpec.CLEARTEXT, // for http
            new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions()
                    .allEnabledCipherSuites().build() // for https
    }));/*  ww w .  j a v  a 2s  .  c  om*/
    factory = new OkUrlFactory(client);
}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

/**
 * The A10 control port has a brain-dead HTTPS stack that is unable to
 * negotiate TLS versions.//from  w w  w .j a v  a2  s.  c o  m
 *
 * @return
 */
List<ConnectionSpec> getA10CompatibleConnectionSpecs() {
    List<ConnectionSpec> list = Lists.newArrayList();

    list.add(new Builder(ConnectionSpec.MODERN_TLS).tlsVersions(TlsVersion.TLS_1_0).build()); // This
    // is
    // essential
    list.add(ConnectionSpec.MODERN_TLS);
    list.add(ConnectionSpec.CLEARTEXT);
    return ImmutableList.copyOf(list);
}

From source file:org.jclouds.docker.config.DockerOkHttpClientSupplier.java

License:Apache License

@Override
public OkHttpClient get() {
    OkHttpClient client = new OkHttpClient();
    ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_0, TlsVersion.TLS_1_1, TlsVersion.TLS_1_2).build();
    ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();
    client.setConnectionSpecs(ImmutableList.of(tlsSpec, cleartextSpec));
    // check if identity and credential are files, to set up sslContext
    if (new File(creds.get().identity).isFile() && new File(creds.get().credential).isFile()) {
        client.setSslSocketFactory(dockerSSLContextSupplier.get().getSocketFactory());
    }/*from  w  w  w . j  a v  a  2 s. c o  m*/
    return client;
}

From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorServiceTest.java

License:Apache License

@Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*exhausted connection specs.*")
public void testSSLConnectionFailsIfOnlyHttpConfigured() throws Exception {
    MockWebServer server = mockWebServer(new MockResponse());
    server.useHttps(sslContext.getSocketFactory(), false);
    Module httpConfigModule = new ConnectionSpecModule(ConnectionSpec.CLEARTEXT);
    PatchApi api = api(PatchApi.class, server.getUrl("/").toString(), httpConfigModule);
    try {/*from  w  ww. ja va 2 s .c om*/
        api.patchNothing("");
    } finally {
        closeQuietly(api);
        server.shutdown();
    }
}

From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorServiceTest.java

License:Apache License

@Test
public void testBothProtocolsSucceedIfSSLAndHTTPConfigured() throws Exception {
    MockWebServer redirectTarget = mockWebServer(new MockResponse());
    MockWebServer server = mockWebServer(new MockResponse().setResponseCode(302).setHeader("Location",
            redirectTarget.getUrl("/").toString()));
    server.useHttps(sslContext.getSocketFactory(), false);
    Module httpConfigModule = new ConnectionSpecModule(ConnectionSpec.CLEARTEXT, ConnectionSpec.MODERN_TLS);
    PatchApi api = api(PatchApi.class, server.getUrl("/").toString(), httpConfigModule);
    try {/*from w w  w  . j ava 2s .c  o m*/
        api.patchNothing("");
        assertEquals(server.getRequestCount(), 1);
        assertEquals(redirectTarget.getRequestCount(), 1);
    } finally {
        closeQuietly(api);
        server.shutdown();
        redirectTarget.shutdown();
    }
}

From source file:org.sonar.runner.impl.OkHttpClientFactory.java

License:Open Source License

static OkHttpClient create(JavaVersion javaVersion) {
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    httpClient.setReadTimeout(READ_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions()
            .allEnabledCipherSuites().supportsTlsExtensions(true).build();
    httpClient.setConnectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    if (javaVersion.isJava7()) {
        // OkHttp executes SSLContext.getInstance("TLS") by default (see
        // https://github.com/square/okhttp/blob/c358656/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java#L616)
        // As only TLS 1.0 is enabled by default in Java 7, the SSLContextFactory must be changed
        // in order to support all versions from 1.0 to 1.2.
        // Note that this is not overridden for Java 8 as TLS 1.2 is enabled by default.
        // Keeping getInstance("TLS") allows to support potential future versions of TLS on Java 8.
        try {/* w  w w. j av  a 2 s  .  com*/
            httpClient.setSslSocketFactory(
                    new Tls12Java7SocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()));
        } catch (Exception e) {
            throw new IllegalStateException("Fail to init TLS context", e);
        }
    }
    return httpClient;
}

From source file:org.sonarqube.ws.client.HttpConnector.java

License:Open Source License

private HttpConnector(Builder builder, JavaVersion javaVersion) {
    this.baseUrl = HttpUrl.parse(builder.url.endsWith("/") ? builder.url : format("%s/", builder.url));
    this.userAgent = builder.userAgent;

    if (isNullOrEmpty(builder.login)) {
        // no login nor access token
        this.credentials = null;
    } else {//from  w  ww . j a  va 2s  . c  o  m
        // password is null when login represents an access token. In this case
        // the Basic credentials consider an empty password.
        this.credentials = Credentials.basic(builder.login, nullToEmpty(builder.password));
    }

    if (builder.proxy != null) {
        this.okHttpClient.setProxy(builder.proxy);
    }
    // proxy credentials can be used on system-wide proxies, so even if builder.proxy is null
    if (isNullOrEmpty(builder.proxyLogin)) {
        this.proxyCredentials = null;
    } else {
        this.proxyCredentials = Credentials.basic(builder.proxyLogin, nullToEmpty(builder.proxyPassword));
    }

    this.okHttpClient.setConnectTimeout(builder.connectTimeoutMs, TimeUnit.MILLISECONDS);
    this.okHttpClient.setReadTimeout(builder.readTimeoutMs, TimeUnit.MILLISECONDS);

    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions()
            .allEnabledCipherSuites().supportsTlsExtensions(true).build();
    this.okHttpClient.setConnectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    if (javaVersion.isJava7()) {
        // OkHttp executes SSLContext.getInstance("TLS") by default (see
        // https://github.com/square/okhttp/blob/c358656/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java#L616)
        // As only TLS 1.0 is enabled by default in Java 7, the SSLContextFactory must be changed
        // in order to support all versions from 1.0 to 1.2.
        // Note that this is not overridden for Java 8 as TLS 1.2 is enabled by default.
        // Keeping getInstance("TLS") allows to support potential future versions of TLS on Java 8.
        try {
            this.okHttpClient.setSslSocketFactory(
                    new Tls12Java7SocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()));
        } catch (Exception e) {
            throw new IllegalStateException("Fail to init TLS context", e);
        }
    }
}