如何通过OkHttpClient拦截器将baseUrl(host)添加到Picasso?

时间:2017-03-01 11:09:08

标签: android picasso okhttp3 okhttp

我有Photo

的对象String imageUrl = "foo.png"

String host = "http://example.com/photos/"

我试图用以下方式加载图片:

mPicasso.load(photo.getImageUrl()).into(mImageView);

public Picasso providesPicasso(OkHttp3Downloader okHttpDownloader) {
        return new Picasso.Builder(context).listener(new Picasso.Listener() {
            @Override
            public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                exception.printStackTrace();
            }
        }).downloader(okHttpDownloader)
          .executor(Executors.newSingleThreadExecutor())//avoid OutOfMemoryError
          .build();
    }

     public OkHttp3Downloader providesPicassoOkHttpClient(Context context) {
            File cacheDir = createDefaultCacheDir(context, BIG_CACHE_PATH);
            long cacheSize = calculateDiskCacheSize(cacheDir);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .cache(new Cache(cacheDir, cacheSize))
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
                            String host = "http://example.com/photos/";
                            HttpUrl newUrl = request.url().newBuilder().host(host + request.url()).build();

                            request = request.newBuilder().url(newUrl).build();
                            return chain.proceed(request);
                        }
                    })
                    .build();
            return new OkHttp3Downloader(okHttpClient);
        }
`

错误:

java.lang.IllegalStateException: Unrecognized type of request: Request{foo.png}
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at com.squareup.picasso.BitmapHunter$2.load(BitmapHunter.java:66)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:206)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:159)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-01 14:06:49.856 19150-19150/com.basicflags W/System.err:     at java.lang.Thread.run(Thread.java:818)

4 个答案:

答案 0 :(得分:3)

也许你可以尝试使用每张照片的照片网址连接基本网址。

public static final String BASE_IMAGE_URL = "//your image host"

...

Picasso.with(getContext()).load(BASE_IMAGE_URL + "image url").into(your imageview);

答案 1 :(得分:3)

此处的问题是Picasso拒绝了您的请求,因为它无法识别Request的类型。所以没有拦截请求。

 W/System.err: java.lang.IllegalStateException: Unrecognized type of request: Request{img_fjords.jpg}

您不应该在Interceptor内转换您的网址,而应该事先这样做。您可以向Picasso.RequestTransformer添加Picasso.Builder。根据文档,RequestTransformer是:

  

在提交每个请求之前立即调用的转换器。这可用于修改有关请求的任何信息。   例如,如果您使用CDN,则可以根据用户的当前位置更改图像的主机名,以便加快下载速度。

public Picasso providesPicasso(OkHttp3Downloader okHttpDownloader) {
    return new Picasso.Builder(context).listener(new Picasso.Listener() {
        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
            exception.printStackTrace();
        }
    })
            .downloader(okHttpDownloader)
            .requestTransformer(new Picasso.RequestTransformer() {
                @Override
                public com.squareup.picasso.Request transformRequest(com.squareup.picasso.Request request) {
                    Log.d(TAG, "nonTransformedRequest: " + request.uri.toString());

                    String host = "https://www.w3schools.com/w3css/";
                    com.squareup.picasso.Request build = new com.squareup.picasso.Request.Builder(Uri.parse(host + request.uri.toString())).build();

                    Log.d(TAG, "transformedRequest: " + build.uri.toString());
                    return build;
                }
            })
            .executor(Executors.newSingleThreadExecutor())//avoid OutOfMemoryError
            .build();
}

您可以在Interceptor

中处理其余部分
public OkHttp3Downloader providesPicassoOkHttpClient(Context context) {
        File cacheDir = createDefaultCacheDir(context, BIG_CACHE_PATH);
        long cacheSize = calculateDiskCacheSize(cacheDir);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cache(new Cache(cacheDir, cacheSize))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Log.d(TAG, "URL in Interceptor: "+request.url());
                        request = request.newBuilder().build();  //ADD HEADERS HERE
                        return chain.proceed(request);
                    }
                })
                .build();
        return new OkHttp3Downloader(okHttpClient);
    }

现在只需按预期使用mPicasso

mPicasso.load(photo.getImageUrl()).into(mImageView);

以下是LOG看起来

的方式
02-15 15:10:14.767 6531-6531/com.smk.stack D/TAG: nonTransformedRequest: img_fjords.jpg
02-15 15:10:14.767 6531-6531/com.smk.stack D/TAG: transformedRequest: https://www.w3schools.com/w3css/img_fjords.jpg
02-15 15:10:14.828 6531-6590/com.smk.stack D/TAG: URL in Interceptor: https://www.w3schools.com/w3css/img_fjords.jpg

答案 2 :(得分:2)

首先,您可以通过拦截器为您的请求添加标题。

 private Interceptor getDefaultHeaderInterceptor() throws IOException {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header(ApiConstants.ACCEPT_LANGUAGE, Locale.getDefault().getLanguage());
                requestBuilder.header(ApiConstants.AUTHORIZATION, oauthTokenStore.getAccessToken());
                return chain.proceed(requestBuilder.build());
            }
        };
    }

你可以像这样创建OkHttpClient。

public OkHttpClient getOkHttpClient() throws IOException {
         OkhttpClient.Builder builder = new Builder()
                        .readTimeout(BuildConfig.CONNECTION_READ_TIMEOUT, TimeUnit.SECONDS)
                        .connectTimeout(BuildConfig.CONNECT_TIMEOUT, TimeUnit.SECONDS)
                        .addInterceptor(getDefaultHeaderInterceptor())
                        .build();

... 最后构建毕加索实例:

public Picasso providePicasso() {
        return new Picasso.Builder(context)
                .downloader(new OkHttp3Downloader(getOkHttpClient()))
                .build();
    }

然后你可以像@faranjit一样使用它告诉你:

providePicasso().load(BASE_IMAGE_URL + "image url").into(your imageview);

答案 3 :(得分:1)

保持简单!你有一个班级Photo?添加方法

public String getFullUrl(Context context) {
  return context.getString(R.string.host) + imageUrl;
}

,将您的主机定义移动到字符串资源中(奖励:您现在可以为不同的配置覆盖它,例如暂存,生产等)。

如果您需要其他标头,请在Interceptor中添加。毕加索使用新方法:

mPicasso.load(photo.getFullUrl(getContext())).into(mImageView);