Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Cookie for Picasso

im trying to set Cookie for picasso connections . i found this for OkHttp:

OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

the problem is i dont know where to set this for Picasso . All ideas accepted ! thanks

like image 391
Aerox Avatar asked Dec 14 '22 20:12

Aerox


2 Answers

You'll want to use OkHttpDownloader to tie the two together:

OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

// Create the downloader for Picasso to use
OkHttpDownloader downloader = new OkHttpDownloader(client);
Picasso picasso = new Picasso.Builder(context).downloader(downloader).build();
like image 81
ianhanniballake Avatar answered Dec 27 '22 13:12

ianhanniballake


Overriding the openConnection-Method from UrlConnectionDownloader worked for me.

import android.content.Context;
import android.net.Uri;
import com.squareup.picasso.UrlConnectionDownloader;
import java.io.IOException;
import java.net.HttpURLConnection;

public  class CookieImageDownloader extends UrlConnectionDownloader{

    public CookieImageDownloader(Context context) {
        super(context);
    }

    @Override
    protected HttpURLConnection openConnection(Uri path) throws IOException{
        HttpURLConnection conn = super.openConnection(path);

        String cookieName = /*your cookie-name */;
        String cookieValue = /*your cookie-value */;
        conn.setRequestProperty("Cookie",cookieName + "=" + cookieValue );

        return conn;
    }
}

To apply it to Picasso:

Picasso picasso = new Picasso.Builder(context).downloader(new CookieImageDownloader(context)).build();

And take care not to use picasso.with() afterwards because it will initialize the builder again removing our custom downloader CookieImageDownloader, but instead, use picasso.load() directly.

like image 44
bastiotutuama Avatar answered Dec 27 '22 12:12

bastiotutuama