android – 如何通过OkHttpClient Interceptor将baseUrl(host)添加到Picasso?

我有对象Photo with String imageUrl =“foo.png”

并有String host =“http://example.com/photos/”

我正在尝试加载图像:

mPicasso.load(photo.getImageUrl())代入(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)

解决方法:

这里的问题是毕加索拒绝你的请求,因为它不承认请求的类型.所以没有拦截请求.

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

你不应该在你的Interceptor中转换你的URL,并且应该事先做到这一点.您可以在Picasso.Builder中添加Picasso.RequestTransformer.根据文档,RequestTransformer是:

A transformer that is called immediately before every request is submitted. This can be used to modify any information about a request.
For example, if you use a CDN you can change the hostname for the image based on the current location of the user in order to get faster download speeds.

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();
}

你可以在你的拦截器中处理其余部分

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
上一篇:基于Okhttp的网络通信的初步认识


下一篇:android – 改造okhttp获取随机eofexception