Set Cookie for Picasso

2019-01-26 16:07发布

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

2条回答
再贱就再见
2楼-- · 2019-01-26 16:45

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-26 16:55

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();
查看更多
登录 后发表回答