android picasso library add token header

后端 未结 1 564
情深已故
情深已故 2021-01-24 04:13

I have been breaking my brain on this one,

I am using Picasso library to load and download images from my server, but now I want to add a header in my download request a

相关标签:
1条回答
  • 2021-01-24 05:04

    Picasso uses OkHttp as engine , or it is possible to configure Picasso to use it, and since you have to set the header of the http request, you can use an Interceptor. E.g. this is my Interceptor to handle basic authentication:

    private static class BasicAuthInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            final Request original = chain.request();
            final Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", "Basic " + BASIC_AUTH_ENCODED)
            .method(original.method(), original.body());
            return chain.proceed(requestBuilder.build());
        }
    }
    

    and the you add the Interceptor to OkHttp like

     OkHttpClient okHttpClient = new OkHttpClient();
     okHttpClient.interceptors().add(new BasicAuthInterceptor());
    

    Last step is to configure Picasso to use okHttpClient. The Picasso's builder provide a method for it :

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

    gradle dependencies:

    compile 'com.squareup.okhttp3:okhttp:3.0.1'
    compile 'com.squareup.picasso:picasso:2.5.0'
    
    0 讨论(0)
提交回复
热议问题