Search in sources :

Example 6 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project keywhiz by square.

the class HttpClients method testSslClient.

/**
   * Create a {@link OkHttpClient} for tests.
   *
   * @param keyStore Use a client certificate from keystore if present. Client certs disabled if null.
   * @param keyStorePassword keyStore password. Client certs disabled if null.
   * @param requestInterceptors Any request interceptors to register with client.
   * @return new http client
   */
private static OkHttpClient testSslClient(@Nullable KeyStore keyStore, @Nullable String keyStorePassword, KeyStore trustStore, List<Interceptor> requestInterceptors) {
    boolean usingClientCert = keyStore != null && keyStorePassword != null;
    SSLContext sslContext;
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(trustStore);
        if (usingClientCert) {
            sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray());
        }
        sslContext = sslContextBuilder.build();
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw Throwables.propagate(e);
    }
    OkHttpClient.Builder client = new OkHttpClient().newBuilder().sslSocketFactory(sslContext.getSocketFactory()).connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).followSslRedirects(false);
    client.followRedirects(false);
    client.retryOnConnectionFailure(false);
    // Won't use cookies and a client certificate at once.
    if (!usingClientCert) {
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        client.cookieJar(new JavaNetCookieJar(cookieManager));
    }
    for (Interceptor interceptor : requestInterceptors) {
        client.networkInterceptors().add(interceptor);
    }
    return client.build();
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) Interceptor(okhttp3.Interceptor) CookieManager(java.net.CookieManager)

Example 7 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project AntennaPod by AntennaPod.

the class AntennapodHttpClient method newBuilder.

/**
     * Creates a new HTTP client.  Most users should just use
     * getHttpClient() to get the standard AntennaPod client,
     * but sometimes it's necessary for others to have their own
     * copy so that the clients don't share state.
     * @return http client
     */
@NonNull
public static OkHttpClient.Builder newBuilder() {
    Log.d(TAG, "Creating new instance of HTTP client");
    System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // detect 301 Moved permanently and 308 Permanent Redirect
    builder.networkInterceptors().add(chain -> {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == HttpURLConnection.HTTP_MOVED_PERM || response.code() == StatusLine.HTTP_PERM_REDIRECT) {
            String location = response.header("Location");
            if (location.startsWith("/")) {
                HttpUrl url = request.url();
                location = url.scheme() + "://" + url.host() + location;
            } else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
                HttpUrl url = request.url();
                String path = url.encodedPath();
                String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
                location = url.scheme() + "://" + url.host() + newPath;
            }
            try {
                DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return response;
    });
    // set cookie handler
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
    builder.cookieJar(new JavaNetCookieJar(cm));
    // set timeouts
    builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    // configure redirects
    builder.followRedirects(true);
    builder.followSslRedirects(true);
    ProxyConfig config = UserPreferences.getProxyConfig();
    if (config.type != Proxy.Type.DIRECT) {
        int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
        SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
        Proxy proxy = new Proxy(config.type, address);
        builder.proxy(proxy);
        if (!TextUtils.isEmpty(config.username)) {
            String credentials = Credentials.basic(config.username, config.password);
            builder.interceptors().add(chain -> {
                Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                return chain.proceed(request);
            });
        }
    }
    if (16 <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < 21) {
        builder.sslSocketFactory(new CustomSslSocketFactory(), trustManager());
    }
    return builder;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Response(okhttp3.Response) Proxy(java.net.Proxy) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CookieManager(java.net.CookieManager) NonNull(android.support.annotation.NonNull)

Example 8 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project keywhiz by square.

the class ClientUtils method sslOkHttpClient.

/**
   * Creates a {@link OkHttpClient} to start a TLS connection.
   *
   * @param devTrustStore if not null, uses the provided TrustStore instead of whatever is
   *                      configured in the JVM. This is a convenient way to allow developers to
   *                      start playing with Keywhiz right away. This option should not be used in
   *                      production systems.
   * @param cookies list of cookies to include in the client.
   * @return new http client.
   */
public static OkHttpClient sslOkHttpClient(@Nullable KeyStore devTrustStore, List<HttpCookie> cookies) {
    checkNotNull(cookies);
    SSLContext sslContext;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(devTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw Throwables.propagate(e);
    }
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    OkHttpClient.Builder client = new OkHttpClient().newBuilder().sslSocketFactory(socketFactory).connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).followSslRedirects(false);
    client.retryOnConnectionFailure(false);
    client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
    cookies.forEach(c -> getCookieManager().getCookieStore().add(null, c));
    client.cookieJar(new JavaNetCookieJar(getCookieManager()));
    return client.build();
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 9 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project okhttp by square.

the class CookiesTest method testCookiesSentIgnoresCase.

@Test
public void testCookiesSentIgnoresCase() throws Exception {
    client = client.newBuilder().cookieJar(new JavaNetCookieJar(new CookieManager() {

        @Override
        public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
            Map<String, List<String>> result = new LinkedHashMap<>();
            result.put("COOKIE", Collections.singletonList("Bar=bar"));
            result.put("cooKIE2", Collections.singletonList("Baz=baz"));
            return result;
        }
    })).build();
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();
    get(server.url("/"));
    RecordedRequest request = server.takeRequest();
    assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
    assertNull(request.getHeader("Cookie2"));
    assertNull(request.getHeader("Quux"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) List(java.util.List) URI(java.net.URI) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CookieManager(java.net.CookieManager) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 10 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project okhttp by square.

the class CookiesTest method receiveAndSendMultipleCookies.

@Test
public void receiveAndSendMultipleCookies() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().addHeader("Set-Cookie", "a=android").addHeader("Set-Cookie", "b=banana"));
    server.enqueue(new MockResponse());
    server.start();
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client = client.newBuilder().cookieJar(new JavaNetCookieJar(cookieManager)).build();
    get(urlWithIpAddress(server, "/"));
    RecordedRequest request1 = server.takeRequest();
    assertNull(request1.getHeader("Cookie"));
    get(urlWithIpAddress(server, "/"));
    RecordedRequest request2 = server.takeRequest();
    assertEquals("a=android; b=banana", request2.getHeader("Cookie"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) CookieManager(java.net.CookieManager) Test(org.junit.Test)

Aggregations

CookieManager (java.net.CookieManager)11 MockResponse (okhttp3.mockwebserver.MockResponse)10 Test (org.junit.Test)9 MockWebServer (okhttp3.mockwebserver.MockWebServer)8 HttpCookie (java.net.HttpCookie)6 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)6 OkHttpClient (okhttp3.OkHttpClient)4 JavaNetCookieJar (okhttp3.JavaNetCookieJar)3 URI (java.net.URI)2 KeyManagementException (java.security.KeyManagementException)2 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Map (java.util.Map)2 SSLContext (javax.net.ssl.SSLContext)2 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)2 NonNull (android.support.annotation.NonNull)1 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)1 Gson (com.google.gson.Gson)1