1

我尝试设置在使用 Picasso 请求图像时发送的 cookie,但它似乎没有通过监视网络中的 HTTP 标头来发送任何 cookie。

我已经如下构建了一个 Picasso 实例,并尝试使用 HttpURLConnection 作为下载器并使用 cookieSyncManager 设置 cookie。

我可能做错了什么?

Builder picassoBuilder = new Picasso.Builder(this);
Downloader downloader = new UrlConnectionDownloader(this);
picassoBuilder.downloader(downloader);

Picasso picasso = picassoBuilder.build();

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();

cookieManager.setCookie("http://example.com/", "key=value");
cookieSyncManager.sync();

picasso.with(this).load("http://example.com/image.php?image=test.png").into(imageView);
4

1 回答 1

0

我终于设法使用 OkHttp 和 OkHttp3Downloader 做到了这一点。您需要使用拦截器,然后在请求(ref)中设置 cookie。此外,您需要手动设置缓存,因为(在某些情况下)在您使用自定义下载器( ref)时不起作用

OkHttpClient client = new OkHttpClient()
    .newBuilder()
    .addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            final Request original = chain.request();

            final Request authorized = original.newBuilder()
                    .addHeader("Cookie", CookieManager.getInstance().getCookie(yourUrl))
                    .addHeader("User-Agent", yourUserAgent)
                    .build();

            return chain.proceed(authorized);
        }
    })
    .cache(new Cache(context.getCacheDir(), 25 * 1024 * 1024))
    .build();



Picasso picasso = new Picasso.Builder(context)
                  .downloader(new OkHttp3Downloader(client))
                  .memoryCache(new LruCache(context))
                  .build();

picasso.load(yourUrlImage).into(yourView);

依赖

compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
于 2017-07-24T08:23:50.680 回答