Search in sources :

Example 1 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project talk-android by nextcloud.

the class RestModule method provideHttpClient.

@Provides
@Singleton
OkHttpClient provideHttpClient(Proxy proxy, AppPreferences appPreferences, MagicTrustManager magicTrustManager, SSLSocketFactoryCompat sslSocketFactoryCompat, Cache cache, CookieManager cookieManager) {
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.connectTimeout(45, TimeUnit.SECONDS);
    httpClient.readTimeout(45, TimeUnit.SECONDS);
    httpClient.writeTimeout(45, TimeUnit.SECONDS);
    httpClient.cookieJar(new JavaNetCookieJar(cookieManager));
    httpClient.cache(cache);
    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addInterceptor(loggingInterceptor);
    }
    httpClient.sslSocketFactory(sslSocketFactoryCompat, magicTrustManager);
    httpClient.retryOnConnectionFailure(true);
    httpClient.hostnameVerifier(magicTrustManager.getHostnameVerifier(OkHostnameVerifier.INSTANCE));
    if (!Proxy.NO_PROXY.equals(proxy)) {
        httpClient.proxy(proxy);
        if (appPreferences.getProxyCredentials() && !TextUtils.isEmpty(appPreferences.getProxyUsername()) && !TextUtils.isEmpty(appPreferences.getProxyPassword())) {
            httpClient.proxyAuthenticator(new ProxyAuthenticator(Credentials.basic(appPreferences.getProxyUsername(), appPreferences.getProxyPassword())));
        }
    }
    httpClient.addInterceptor(new HeadersInterceptor());
    return httpClient.build();
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 2 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project talk-android by nextcloud.

the class AccountRemovalJob method onRunJob.

@NonNull
@Override
protected Result onRunJob(Params params) {
    NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
    PushConfigurationState pushConfigurationState;
    for (Object userEntityObject : userUtils.getUsersScheduledForDeletion()) {
        UserEntity userEntity = (UserEntity) userEntityObject;
        try {
            if (!TextUtils.isEmpty(userEntity.getPushConfigurationState())) {
                pushConfigurationState = LoganSquare.parse(userEntity.getPushConfigurationState(), PushConfigurationState.class);
                PushConfigurationState finalPushConfigurationState = pushConfigurationState;
                ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
                ncApi.unregisterDeviceForNotificationsWithNextcloud(ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()), ApiUtils.getUrlNextcloudPush(userEntity.getBaseUrl())).subscribe(new Observer<GenericOverall>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(GenericOverall genericOverall) {
                        if (genericOverall.getOcs().getMeta().getStatusCode() == 200 || genericOverall.getOcs().getMeta().getStatusCode() == 202) {
                            HashMap<String, String> queryMap = new HashMap<>();
                            queryMap.put("deviceIdentifier", finalPushConfigurationState.deviceIdentifier);
                            queryMap.put("userPublicKey", finalPushConfigurationState.getUserPublicKey());
                            queryMap.put("deviceIdentifierSignature", finalPushConfigurationState.getDeviceIdentifierSignature());
                            ncApi.unregisterDeviceForNotificationsWithProxy(ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()), ApiUtils.getUrlPushProxy(), queryMap).subscribe(new Observer<Void>() {

                                @Override
                                public void onSubscribe(Disposable d) {
                                }

                                @Override
                                public void onNext(Void aVoid) {
                                    userUtils.deleteUser(userEntity.getUsername(), userEntity.getBaseUrl()).subscribe(new CompletableObserver() {

                                        @Override
                                        public void onSubscribe(Disposable d) {
                                        }

                                        @Override
                                        public void onComplete() {
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                        }
                                    });
                                }

                                @Override
                                public void onError(Throwable e) {
                                }

                                @Override
                                public void onComplete() {
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
            } else {
                userUtils.deleteUser(userEntity.getUsername(), userEntity.getBaseUrl()).subscribe(new CompletableObserver() {

                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
            }
        } catch (IOException e) {
            Log.d(TAG, "Something went wrong while removing job at parsing PushConfigurationState");
            userUtils.deleteUser(userEntity.getUsername(), userEntity.getBaseUrl()).subscribe(new CompletableObserver() {

                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void onError(Throwable e) {
                }
            });
        }
    }
    return Result.SUCCESS;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) Disposable(io.reactivex.disposables.Disposable) HashMap(java.util.HashMap) IOException(java.io.IOException) UserEntity(com.nextcloud.talk.models.database.UserEntity) PushConfigurationState(com.nextcloud.talk.models.json.push.PushConfigurationState) CompletableObserver(io.reactivex.CompletableObserver) Observer(io.reactivex.Observer) CompletableObserver(io.reactivex.CompletableObserver) NcApi(com.nextcloud.talk.api.NcApi) GenericOverall(com.nextcloud.talk.models.json.generic.GenericOverall) CookieManager(java.net.CookieManager) NonNull(android.support.annotation.NonNull)

Example 3 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project talk-android by nextcloud.

the class CapabilitiesJob method onRunJob.

@NonNull
@Override
protected Result onRunJob(Params params) {
    NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
    long internalUserId = getParams().getExtras().getLong(BundleKeys.KEY_INTERNAL_USER_ID, -1);
    UserEntity userEntity;
    List userEntityObjectList = new ArrayList();
    if (internalUserId == -1 || (userEntity = userUtils.getUserWithInternalId(internalUserId)) == null) {
        userEntityObjectList = userUtils.getUsers();
    } else {
        userEntityObjectList.add(userEntity);
    }
    for (Object userEntityObject : userEntityObjectList) {
        UserEntity internalUserEntity = (UserEntity) userEntityObject;
        ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new JavaNetCookieJar(new java.net.CookieManager())).build()).build().create(NcApi.class);
        ncApi.getCapabilities(ApiUtils.getCredentials(internalUserEntity.getUsername(), internalUserEntity.getToken()), ApiUtils.getUrlForCapabilities(internalUserEntity.getBaseUrl())).subscribeOn(Schedulers.newThread()).subscribe(new Observer<CapabilitiesOverall>() {

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(CapabilitiesOverall capabilitiesOverall) {
                updateUser(capabilitiesOverall, internalUserEntity);
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }
    return Result.SUCCESS;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) Disposable(io.reactivex.disposables.Disposable) ArrayList(java.util.ArrayList) UserEntity(com.nextcloud.talk.models.database.UserEntity) CapabilitiesOverall(com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall) ArrayList(java.util.ArrayList) List(java.util.List) NcApi(com.nextcloud.talk.api.NcApi) NonNull(android.support.annotation.NonNull)

Example 4 with JavaNetCookieJar

use of okhttp3.JavaNetCookieJar in project opacclient by opacapp.

the class HttpClientFactory method getOkHttpClientBuilder.

protected OkHttpClient.Builder getOkHttpClientBuilder(boolean customssl, boolean tls_only, boolean allCipherSuites) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    builder.cookieJar(new JavaNetCookieJar(cookieManager));
    builder.addNetworkInterceptor(new CustomRedirectInterceptor());
    builder.connectTimeout(60, TimeUnit.SECONDS);
    builder.readTimeout(60, TimeUnit.SECONDS);
    builder.writeTimeout(60, TimeUnit.SECONDS);
    if (customssl && ssl_store_path != null) {
        try {
            if (trust_store == null) {
                trust_store = getKeyStore();
            }
            X509TrustManager trustManager = new AdditionalKeyStoresSSLSocketFactory.AdditionalKeyStoresTrustManager(trust_store);
            SSLSocketFactory sf = AdditionalKeyStoresSSLSocketFactory.createForOkHttp(trustManager);
            if (allCipherSuites) {
                sf = new AllCiphersProxySocketFactory(sf);
            }
            sf = new TLS12ProxySocketFactory(sf);
            builder.sslSocketFactory(sf, trustManager);
            List<ConnectionSpec> connectionSpecs = new ArrayList<ConnectionSpec>();
            connectionSpecs.add(ConnectionSpec.MODERN_TLS);
            connectionSpecs.add(new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS).allEnabledCipherSuites().build());
            if (!tls_only) {
                connectionSpecs.add(new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS).tlsVersions(TlsVersion.SSL_3_0, TlsVersion.TLS_1_0).allEnabledCipherSuites().build());
            } else if (allCipherSuites) {
                connectionSpecs.add(new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS).allEnabledCipherSuites().build());
            }
            connectionSpecs.add(ConnectionSpec.CLEARTEXT);
            builder.connectionSpecs(connectionSpecs);
            return builder;
        } catch (Exception e) {
            e.printStackTrace();
            return builder;
        }
    } else {
        try {
            X509TrustManager trustManager = getSystemDefaultTrustManager();
            SSLSocketFactory socketFactory = getSystemDefaultSSLSocketFactory(trustManager);
            builder.sslSocketFactory(new TLS12ProxySocketFactory(socketFactory), trustManager);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ignored) {
        }
        return builder;
    }
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) RegistryBuilder(org.apache.http.config.RegistryBuilder) RequestBuilder(org.apache.http.client.methods.RequestBuilder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CircularRedirectException(org.apache.http.client.CircularRedirectException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) KeyManagementException(java.security.KeyManagementException) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) CookieManager(java.net.CookieManager)

Example 5 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 == null) {
                return response;
            }
            if (location.startsWith("/")) {
                // URL is not absolute, but relative
                HttpUrl url = request.url();
                location = url.scheme() + "://" + url.host() + location;
            } else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
                // Reference is relative to current path
                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;
    });
    builder.interceptors().add(new BasicAuthorizationInterceptor());
    builder.networkInterceptors().add(new UserAgentInterceptor());
    // 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);
    // 20MB
    builder.cache(new Cache(cacheDirectory, 20L * 1000000));
    // configure redirects
    builder.followRedirects(true);
    builder.followSslRedirects(true);
    ProxyConfig config = UserPreferences.getProxyConfig();
    if (config.type != Proxy.Type.DIRECT && !TextUtils.isEmpty(config.host)) {
        int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
        SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
        builder.proxy(new Proxy(config.type, address));
        if (!TextUtils.isEmpty(config.username) && config.password != null) {
            builder.proxyAuthenticator((route, response) -> {
                String credentials = Credentials.basic(config.username, config.password);
                return response.request().newBuilder().header("Proxy-Authorization", credentials).build();
            });
        }
    }
    SslClientSetup.installCertificates(builder);
    return builder;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) UserAgentInterceptor(de.danoeh.antennapod.core.service.UserAgentInterceptor) Request(okhttp3.Request) BasicAuthorizationInterceptor(de.danoeh.antennapod.core.service.BasicAuthorizationInterceptor) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) Proxy(java.net.Proxy) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CookieManager(java.net.CookieManager) Cache(okhttp3.Cache) NonNull(androidx.annotation.NonNull)

Aggregations

JavaNetCookieJar (okhttp3.JavaNetCookieJar)10 CookieManager (java.net.CookieManager)8 OkHttpClient (okhttp3.OkHttpClient)7 NonNull (android.support.annotation.NonNull)3 NcApi (com.nextcloud.talk.api.NcApi)3 UserEntity (com.nextcloud.talk.models.database.UserEntity)3 Disposable (io.reactivex.disposables.Disposable)3 IOException (java.io.IOException)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 X509TrustManager (javax.net.ssl.X509TrustManager)3 PushConfigurationState (com.nextcloud.talk.models.json.push.PushConfigurationState)2 Provides (dagger.Provides)2 Observer (io.reactivex.Observer)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)2 Cache (okhttp3.Cache)2 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)2