Set Cookie for Picasso

后端 未结 2 695
慢半拍i
慢半拍i 2020-12-19 14:54

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

OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new Cooki         


        
相关标签:
2条回答
  • 2020-12-19 15:39

    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.

    0 讨论(0)
  • 2020-12-19 15:45

    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();
    
    0 讨论(0)
提交回复
热议问题