使用Picasso的自定义下载器

时间:2014-07-27 13:30:50

标签: android image picasso

我必须从URL下载图像,该图片需要一些标题(用户名,密码)以及请求。所以我正在使用here给出的代码。但调用此函数会产生错误

java.lang.NoClassDefFoundError: com.squareup.okhttp.OkHttpClient
at com.squareup.picasso.OkHttpDownloader.<init>(OkHttpDownloader.java:72)

我正在使用Picasso 2.3.3和okhttp-urlconnection-2.0.0-RC2库 问题已在this帖子中提出,但更改为2.3.2无效。

2 个答案:

答案 0 :(得分:7)

你的项目中是否包含OkHttp?如果没有,问题是你正在使用OkHttpDownloader。您可以在项目中包含OkHttp库,也可以在下面添加UrlConnectionDownloader。

这是我最终的结果。

public static Picasso getImageLoader(Context ctx) {
    Picasso.Builder builder = new Picasso.Builder(ctx);

    builder.downloader(new UrlConnectionDownloader(ctx) {
        @Override
        protected HttpURLConnection openConnection(Uri uri) throws IOException {
            HttpURLConnection connection = super.openConnection(uri);
            connection.setRequestProperty("X-HEADER", "VAL");
            return connection;
        }
    });

    return builder.build();
}

答案 1 :(得分:4)

由于Picasso 2.5.0 OkHttpDownloader类已被更改,因此您必须执行以下操作:

OkHttpClient picassoClient = new OkHttpClient();

picassoClient.networkinterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request newRequest = chain.request().newBuilder()
                    .addHeader("X-HEADER", "VAL")
                    .build();
            return chain.proceed(newRequest);
        }
});

new Picasso.Builder(context).downloader(new OkHttpDownloader(picassoClient)).build();

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