Android Picasso 库,如何添加身份验证 header ?

标签 android picasso okhttp

我尝试使用自定义身份验证器设置自定义 OkHttpClient,但是正如文档所说:“响应来自远程 Web 或代理服务器的身份验证挑战。”我必须对每张图片提出 2 个请求,这并不理想。

有没有像 Retrofit 这样的请求拦截器?还是我在 OkHttpClient 中遗漏了什么?

我使用的是最新版本:

compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.squareup.okhttp:okhttp:2.0.+'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.+'
compile 'com.squareup.okio:okio:1.0.0'

谢谢!

最佳答案

由于 Picasso 2.5.0 OkHttpDownloader 类已更改,假设您使用的是 OkHttp3(因此 picasso2-okhttp3-downloader ),因此您必须执行以下操作:

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder()
                        .addHeader("X-TOKEN", "VAL")
                        .build();
                return chain.proceed(newRequest);
            }
        })
        .build();

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

来源:https://github.com/square/picasso/issues/900

关于Android Picasso 库,如何添加身份验证 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24273783/

相关文章:

android - picasso 清晰的内存

android - OkHttp 半闭流用于 Android 上 AVS 的下行 channel

android - 改变 View 高度的流畅动画

Android 如何在 LocationManager 中获取高度。我总是归零

android - 如何使 LayerDrawable(图层列表项)在 Android 上不可见?

java - Recyclerview 从 Picasso 加载缓存的图像非常缓慢

android - 使用 Picasso 库从 https url 加载图像时出错

java - 如果服务器返回 5xx 或关闭 (404),OkHttp 返回缓存的响应

android - Retrofit 2 和 okhttp 3 的缓存错误

android - 无法使用 cordova fileopener 插件打开本地文件