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

gon*_*lov 33 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'
Run Code Online (Sandbox Code Playgroud)

谢谢!

bry*_*410 85

由于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();
Run Code Online (Sandbox Code Playgroud)

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

  • 另外,当您使用新的毕加索实例时,请不要使用.with(context),因为这将撤消自定义拦截器. (6认同)
  • 您可以从https://github.com/JakeWharton/picasso2-okhttp3-downloader获取OkHttp3Downloader (3认同)
  • 在第一行中,您在'OkHttpClient();'之前错过了'new' (2认同)
  • 请注意,最新的okhttpclient版本为3,与picasso 2不兼容.如果要使用此解决方案,则需要okhttpclient 2. (2认同)
  • `networkInterceptors`是OkHttp3中的一个不可变列表,你无法直接添加它,你需要使用一个构建器.`OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); builder.networkInterceptors().add(...); client = builder.build()`. (2认同)

nha*_*man 8

有关更新的解决方案,请参阅bryant1410的答案.


这样的事情可以用来设置API密钥头:

public class CustomPicasso {

    private static Picasso sPicasso;

    private CustomPicasso() {
    }

    public static Picasso getImageLoader(final Context context) {
        if (sPicasso == null) {
            Picasso.Builder builder = new Picasso.Builder(context);
            builder.downloader(new CustomOkHttpDownloader());
            sPicasso = builder.build();
        }
        return sPicasso;
    }

    private static class CustomOkHttpDownloader extends OkHttpDownloader {

        @Override
        protected HttpURLConnection openConnection(final Uri uri) throws IOException {
            HttpURLConnection connection = super.openConnection(uri);
            connection.setRequestProperty(Constants.HEADER_X_API_KEY, "MY_API_KEY");
            return connection;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)