question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to Keep Session in Fresco with OKHTTP or Add Cookie Before Image URI call?

See original GitHub issue

I login my server use retrofit with okhttp I login using the Retrofit with okhttp to the server . and I save Cookie at Preferences.

client = new OkHttpClient();
client.interceptors().add(new AddCookiesInterceptor());
client.interceptors().add(new ReceivedCookiesInterceptor());

AddCookiesInterceptor.java

public class AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) PreferenceHelper.getDefaultPreferences().getStringSet(PreferenceHelper.PREF_COOKIES, new HashSet<String>());
        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
            Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
        }

        return chain.proceed(builder.build());
    }
}

ReceivedCookiesInterceptor.java

public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
            }


            PreferenceHelper.getDefaultPreferences().edit()
                    .putStringSet(PreferenceHelper.PREF_COOKIES, cookies)
                    .apply();

        }

        return originalResponse;
    }
}

And then I initialize Fresco.

ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
    .newBuilder(this, CustomRestAdapter.getClient())
    .build();
 Fresco.initialize(this , config);

...

public static DirectFoldertInterface getInstance() {
    if (DirectFoldertInterface == null) {
        client = new OkHttpClient();
        client.setConnectTimeout(1500, TimeUnit.MILLISECONDS);
        client.setWriteTimeout(1500, TimeUnit.MILLISECONDS);
        client.setReadTimeout(1500, TimeUnit.MILLISECONDS);
        client.interceptors().add(new AddCookiesInterceptor());
        client.interceptors().add(new ReceivedCookiesInterceptor());
}

But Fresco can’t load Image. I Think The Problem is cookie. How to Keep Session in Fresco with OKHTTP or Add Cookie Before Image URI call?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:8

github_iconTop GitHub Comments

7reactions
leeyc09commented, Oct 14, 2015

@kirtov I solved this problem. right this. Client Setting

client = configureClient(new OkHttpClient());
client.setConnectTimeout(15000, TimeUnit.MILLISECONDS);
client.setWriteTimeout(15000, TimeUnit.MILLISECONDS);
client.setReadTimeout(15000, TimeUnit.MILLISECONDS);
client.setCookieHandler(new MyCookieManager());
client.interceptors().add(new DCB_AddCookiesInterceptor());
client.interceptors().add(new DCB_ReceivedCookiesInterceptor());

MyCookieManager

package com.jiran.directcloud.note.net;

import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2015-06-12.
 */
public class MyCookieManager extends CookieManager {

    // The cookie key we're interested in.
    private final String SESSION_KEY = "session-key";
    private final String SET_COOKIE_KEY = "Set-Cookie";


    /**
     * Creates a new instance of this cookie manager accepting all cookies.
     */
    public MyCookieManager() {
        super.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {

        super.put(uri, responseHeaders);

        if (responseHeaders == null || responseHeaders.get(SET_COOKIE_KEY) == null) {
            // No cookies in this response, simply return from this method.
            return;
        }

        // Yes, we've found cookies, inspect them for the key we're looking for.
        for (String possibleSessionCookieValues : responseHeaders.get(SET_COOKIE_KEY)) {

            if (possibleSessionCookieValues != null) {

                for (String possibleSessionCookie : possibleSessionCookieValues.split(";")) {

                    if (possibleSessionCookie.startsWith(SESSION_KEY) && possibleSessionCookie.contains("=")) {

                        // We can safely get the index 1 of the array: we know it contains
                        // a '=' meaning it has at least 2 values after splitting.
                        String session = possibleSessionCookie.split("=")[1];

                        // store `session` somewhere

                        return;
                    }
                }
            }
        }
    }

}

DCB_AddCookiesInterceptor

package com.jiran.directcloud.note.net.DCB;

/**
 * Created by user on 2015-06-17.
 */

import com.jiran.directcloud.note.utils.PreferenceHelper;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashSet;

import timber.log.Timber;

/**
 * This interceptor put all the Cookies in Preferences in the Request.
 * Your implementation on how to get the Preferences MAY VARY.
 * <p>
 */
public class DCB_AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) PreferenceHelper.getDefaultPreferences().getStringSet(PreferenceHelper.PREF_BOX_COOKIES, new HashSet<String>());
        int count = 1;
        for (String cookie : preferences) {
            builder.addHeader("Cookie" + count, cookie);
            Timber.d("DCB_AddCookiesInterceptorr-" + count + ": " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
            count++;
        }

        return chain.proceed(builder.build());
    }
}

DCB_ReceivedCookiesInterceptor

package com.jiran.directcloud.note.net.DCB;

import com.jiran.directcloud.note.utils.PreferenceHelper;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashSet;

import timber.log.Timber;


/**
 * This Interceptor add all received Cookies to the app DefaultPreferences.
 * Your implementation on how to save the Cookies on the Preferences MAY VARY.
 * <p>
 * Created by tsuharesu on 4/1/15.
 */
public class DCB_ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
                Timber.d("DCB_ReceivedCookiesInterceptor : " + header); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp


            }

            PreferenceHelper.getDefaultPreferences().edit().putStringSet(PreferenceHelper.PREF_BOX_COOKIES, cookies).apply();

        }

        return originalResponse;
    }
}
0reactions
Omar-Percommented, May 10, 2022

I am doing this request :

              Request request1 = new Request.Builder()
                                .url(authUrl)
                                .method("GET", null)
                                .addHeader("Accept", "application/json")
                                .build();
              Response response = client.newCall(request1).execute();
              String retreivedCookie = "";
              
              
              Request request2 = new Request.Builder()
	                  .url(csrfUrl)
	                  .method("GET", null)
	                  .addHeader("Cookie", "retreivedCookie")
	                  .build();
              Response sbCSRFresponse = client.newCall(request2).execute();

But how to get the cookies that the server returned me? I just want to store it on a String variable (retreivedCookie ) and reuse on the second request

Thank you in advance !

Read more comments on GitHub >

github_iconTop Results From Across the Web

Add cookie to client request OkHttp - android - Stack Overflow
There are 2 ways you can do this: OkHttpClient client = new OkHttpClient().newBuilder() .cookieJar(new CookieJar() { @Override public void ...
Read more >
Using Other Network Layers - Fresco
Handling sessions and cookies correctly. The OkHttpClient you pass to Fresco in the above step should be set up with interceptors needed to...
Read more >
Maintain cookie session in Android(Retrofit) - Nanostuffs
A session is a sequence of requests made by a single end-user ... So, we need to keep the cookie from one call...
Read more >
check the crashlytics plugin to make sure that the application has ...
Open your Firebase project at the Google console and click 'Add app' to add an iOS and / or Android app. Follow the...
Read more >
Free Automated Malware Analysis Service - powered by Falcon ...
Re-analyze Hash Not Seen Before ... Not all malicious and suspicious indicators are displayed. ... Has the ability to query the phone location...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found