android picasso library add token header

2019-02-28 04:55发布

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 and I cant seem to find a way of doing it. all i want to do is set a header like : setHeader("Authorization", "Bearer " + token);

I use this header in any of my server requests, but cant find a way to add it to the picasso line.

Any help would be appreciated, Thanks!

1条回答
迷人小祖宗
2楼-- · 2019-02-28 05:11

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'
查看更多
登录 后发表回答