Search in sources :

Example 16 with CookieJar

use of okhttp3.CookieJar in project WanAndroid by dangxy.

the class RetrofitWanAndroid method okhttpClient.

public OkHttpClient okhttpClient(Context mContext) {
    File cacheFile = new File(mContext.getCacheDir(), "wan-android");
    Cache cache = new Cache(cacheFile, CACHE_SIZE);
    OkHttpClient okHttpClient = null;
    try {
        okHttpClient = new OkHttpClient.Builder().cache(cache).connectTimeout(TIMEOUT_CONNECT, TimeUnit.MILLISECONDS).addInterceptor(new HttpLoggingInterceptor().setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE)).addInterceptor(new LoggingInterceptor()).cookieJar(cookieJar).addNetworkInterceptor(mCacheControlInterceptor).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return okHttpClient;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) File(java.io.File) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) IOException(java.io.IOException) Cache(okhttp3.Cache) SetCookieCache(com.dangxy.wanandroid.api.cache.SetCookieCache)

Example 17 with CookieJar

use of okhttp3.CookieJar 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 18 with CookieJar

use of okhttp3.CookieJar 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 19 with CookieJar

use of okhttp3.CookieJar in project TumCampusApp by TCA-Team.

the class Helper method getOkClient.

public static OkHttpClient getOkClient(Context c) {
    if (client != null) {
        return client;
    }
    final CertificatePinner certificatePinner = new CertificatePinner.Builder().add(API_HOSTNAME, // Fakultaet fuer Informatik
    "sha256/dVphPQ9xG7woPpEKXrNalw4eMUQ4Fw9r3OXTzxfuL5A=").add(API_HOSTNAME, // Technische Universitaet Muenchen
    "sha256/SwdQoHL7SB/6o12XsIhbQJ9bANVnbrJoHTLzlu/qXT0=").add(API_HOSTNAME, // DFN-Verein PCA Global
    "sha256/VzL+FtAKvzb4N5igmFJyv83GD7CBK7Yyw+R6XdRRfmg=").add(API_HOSTNAME, // Deutsche Telekom Root CA 2
    "sha256/0d4q5hyN8vpiOWYWPUxz1GC/xCjldYW+a/65pWMj0bY=").add(API_HOSTNAME, // Let's Encrypt Authority X3
    "sha256/YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=").add(API_HOSTNAME, // LE Cross Sign: DST Root CA X3
    "sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=").add(API_HOSTNAME_NEW, // Fakultaet fuer Informatik
    "sha256/dVphPQ9xG7woPpEKXrNalw4eMUQ4Fw9r3OXTzxfuL5A=").add(API_HOSTNAME_NEW, // Technische Universitaet Muenchen
    "sha256/SwdQoHL7SB/6o12XsIhbQJ9bANVnbrJoHTLzlu/qXT0=").add(API_HOSTNAME_NEW, // DFN-Verein PCA Global
    "sha256/VzL+FtAKvzb4N5igmFJyv83GD7CBK7Yyw+R6XdRRfmg=").add(API_HOSTNAME_NEW, // Deutsche Telekom Root CA 2
    "sha256/0d4q5hyN8vpiOWYWPUxz1GC/xCjldYW+a/65pWMj0bY=").add(API_HOSTNAME_NEW, // Let's Encrypt Authority X3
    "sha256/YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=").add(API_HOSTNAME_NEW, // LE Cross Sign: DST Root CA X3
    "sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=").add(STUDYROOM_HOST, // wwwv2.tum.de
    "sha256/dVphPQ9xG7woPpEKXrNalw4eMUQ4Fw9r3OXTzxfuL5A=").add(STUDYROOM_HOST, // wwwv4.tum.de
    "sha256/K64RzAqr/RSxwfpHN6fe0DcmdaIVmzAyi511ufYaK1s=").add(STUDYROOM_HOST, // Zertifizierungsstelle der TUM
    "sha256/SwdQoHL7SB/6o12XsIhbQJ9bANVnbrJoHTLzlu/qXT0=").add(STUDYROOM_HOST, // DFN-Verein PCA Global - G01
    "sha256/VzL+FtAKvzb4N5igmFJyv83GD7CBK7Yyw+R6XdRRfmg=").add(STUDYROOM_HOST, // Deutsche Telekom Root CA 2
    "sha256/0d4q5hyN8vpiOWYWPUxz1GC/xCjldYW+a/65pWMj0bY=").build();
    // We want to persist our cookies through app session
    ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(c));
    // Start building the http client
    OkHttpClient.Builder builder = new OkHttpClient.Builder().cookieJar(cookieJar).certificatePinner(certificatePinner);
    // Add the device identifying header
    builder.addInterceptor(Helper.getDeviceInterceptor(c));
    builder.connectTimeout(Helper.HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(Helper.HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.addNetworkInterceptor(new TumHttpLoggingInterceptor(message -> Utils.logwithTag(TAG, message)));
    // Save it to the static handle and return
    client = builder.build();
    return client;
}
Also used : Context(android.content.Context) Interceptor(okhttp3.Interceptor) SetCookieCache(com.franmontiel.persistentcookiejar.cache.SetCookieCache) Request(okhttp3.Request) PersistentCookieJar(com.franmontiel.persistentcookiejar.PersistentCookieJar) API_HOSTNAME_NEW(de.tum.in.tumcampusapp.utils.Const.API_HOSTNAME_NEW) PackageManager(android.content.pm.PackageManager) SharedPrefsCookiePersistor(com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor) STUDYROOM_HOST(de.tum.in.tumcampusapp.component.ui.studyroom.StudyRoomGroupManager.STUDYROOM_HOST) UrlEscapers(com.google.common.net.UrlEscapers) CertificatePinner(okhttp3.CertificatePinner) ClearableCookieJar(com.franmontiel.persistentcookiejar.ClearableCookieJar) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Utils(de.tum.in.tumcampusapp.utils.Utils) API_HOSTNAME(de.tum.in.tumcampusapp.utils.Const.API_HOSTNAME) Build(android.os.Build) ClearableCookieJar(com.franmontiel.persistentcookiejar.ClearableCookieJar) OkHttpClient(okhttp3.OkHttpClient) PersistentCookieJar(com.franmontiel.persistentcookiejar.PersistentCookieJar) CertificatePinner(okhttp3.CertificatePinner) SetCookieCache(com.franmontiel.persistentcookiejar.cache.SetCookieCache) SharedPrefsCookiePersistor(com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor)

Example 20 with CookieJar

use of okhttp3.CookieJar in project edx-app-android by edx.

the class NoCacheHeaderStrippingInterceptor method intercept.

@NonNull
@Override
public Response intercept(@NonNull final Chain chain) throws IOException {
    final Request request = chain.request();
    final Response response = chain.proceed(request);
    final Headers headers = response.headers();
    Headers.Builder strippedHeadersBuilder = null;
    List<String> headersToStrip = null;
    for (int i = 0, headersCount = headers.size(); i < headersCount; i++) {
        final String headerName = headers.name(i);
        final String headerValue = headers.value(i);
        if (headerName.equalsIgnoreCase("Cache-Control")) {
            Matcher directiveMatcher = PATTERN_NO_CACHE_HEADER.matcher(headerValue);
            if (directiveMatcher.find()) {
                if (strippedHeadersBuilder == null) {
                    strippedHeadersBuilder = new Headers.Builder();
                    for (int j = 0; j < i; j++) {
                        strippedHeadersBuilder.add(headers.name(j), headers.value(j));
                    }
                    headersToStrip = new ArrayList<>();
                }
                String newHeaderValue = headerValue;
                while (true) {
                    Collections.addAll(headersToStrip, directiveMatcher.group(GROUP_NO_CACHE_HEADERS).trim().split("\\s*,\\s*"));
                    final StringBuffer newHeaderValueBuffer = new StringBuffer();
                    directiveMatcher.appendReplacement(newHeaderValueBuffer, "$" + (directiveMatcher.group(GROUP_SEPARATOR_START).isEmpty() ? GROUP_SEPARATOR_END : GROUP_SEPARATOR_START));
                    directiveMatcher.appendTail(newHeaderValueBuffer);
                    newHeaderValue = newHeaderValueBuffer.toString();
                    directiveMatcher = PATTERN_NO_CACHE_HEADER.matcher(newHeaderValue);
                    if (!directiveMatcher.find())
                        break;
                }
                if (!newHeaderValue.isEmpty()) {
                    strippedHeadersBuilder.add(headerName, newHeaderValue);
                }
                continue;
            }
        }
        if (strippedHeadersBuilder != null) {
            strippedHeadersBuilder.add(headerName, headerValue);
        }
    }
    if (strippedHeadersBuilder == null) {
        return response;
    }
    final HttpUrl url = request.url();
    List<Cookie> cookies = null;
    for (final String headerToStrip : headersToStrip) {
        strippedHeadersBuilder.removeAll(headerToStrip);
        if (headerToStrip.equalsIgnoreCase("Set-Cookie")) {
            if (cookieJar != CookieJar.NO_COOKIES) {
                for (final String cookieString : headers.values(headerToStrip)) {
                    Cookie cookie = Cookie.parse(url, cookieString);
                    if (cookie != null) {
                        if (cookies == null) {
                            cookies = new ArrayList<>();
                        }
                        cookies.add(cookie);
                    }
                }
            }
        }
    }
    if (cookies != null) {
        cookieJar.saveFromResponse(url, cookies);
    }
    return response.newBuilder().headers(strippedHeadersBuilder.build()).build();
}
Also used : Cookie(okhttp3.Cookie) Matcher(java.util.regex.Matcher) Headers(okhttp3.Headers) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) NonNull(android.support.annotation.NonNull)

Aggregations

Test (org.junit.Test)17 MockResponse (okhttp3.mockwebserver.MockResponse)16 OkHttpClient (okhttp3.OkHttpClient)14 CookieManager (java.net.CookieManager)11 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)9 HttpCookie (java.net.HttpCookie)8 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)8 MockWebServer (okhttp3.mockwebserver.MockWebServer)8 Request (okhttp3.Request)6 Response (okhttp3.Response)5 NonNull (android.support.annotation.NonNull)4 IOException (java.io.IOException)4 List (java.util.List)4 CookieHashSet (me.postaddict.instagram.scraper.cookie.CookieHashSet)4 DefaultCookieJar (me.postaddict.instagram.scraper.cookie.DefaultCookieJar)4 ErrorInterceptor (me.postaddict.instagram.scraper.interceptor.ErrorInterceptor)4 UserAgentInterceptor (me.postaddict.instagram.scraper.interceptor.UserAgentInterceptor)4 Cookie (okhttp3.Cookie)4 JavaNetCookieJar (okhttp3.JavaNetCookieJar)4 ClearableCookieJar (com.franmontiel.persistentcookiejar.ClearableCookieJar)3