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

Created on 17 Jun 2015  ·  7Comments  ·  Source: facebook/fresco

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?

bug

Most helpful comment

@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;
    }
}

All 7 comments

Hello, did you solve this problem? I have the same...

@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;
    }
}

Ok, thx very much!

Hey please can you help me for doing this with retrofit as with request i have to send the cookie which i have received from earlier response and how to save that cookie in preference.

Can i get your preferencehlper code ? My email is [email protected].

不错,谢谢

阿里嘎多~

Was this page helpful?
0 / 5 - 0 ratings