Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Picasso library, How to add authentication headers?

I have tried setting a custom OkHttpClient with a custom Authenticator, however as the doc says: "Responds to authentication challenges from the remote web or proxy server." I have to make 2 requests for each image, and that is not ideal.

Is there a request interceptor like Retrofit does? Or am I missing something in the OkHttpClient?

I'm using the latest versions:

compile 'com.squareup.picasso:picasso:2.3.2' compile 'com.squareup.okhttp:okhttp:2.0.+' compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.+' compile 'com.squareup.okio:okio:1.0.0' 

Thanks!

like image 695
gonzalomelov Avatar asked Jun 17 '14 21:06

gonzalomelov


2 Answers

Since Picasso 2.5.0 OkHttpDownloader class has been changed, assuming you are using OkHttp3 (and so picasso2-okhttp3-downloader), so you have to do something like this:

OkHttpClient client = new OkHttpClient.Builder()         .addInterceptor(new Interceptor() {             @Override             public Response intercept(Chain chain) throws IOException {                 Request newRequest = chain.request().newBuilder()                         .addHeader("X-TOKEN", "VAL")                         .build();                 return chain.proceed(newRequest);             }         })         .build();  Picasso picasso = new Picasso.Builder(context)         .downloader(new OkHttp3Downloader(client))         .build(); 

Source: https://github.com/square/picasso/issues/900

like image 133
bryant1410 Avatar answered Sep 23 '22 16:09

bryant1410


See bryant1410's answer for a more up-to-date solution.


Something like this does the job for setting an API-key header:

public class CustomPicasso {      private static Picasso sPicasso;      private CustomPicasso() {     }      public static Picasso getImageLoader(final Context context) {         if (sPicasso == null) {             Picasso.Builder builder = new Picasso.Builder(context);             builder.downloader(new CustomOkHttpDownloader());             sPicasso = builder.build();         }         return sPicasso;     }      private static class CustomOkHttpDownloader extends OkHttpDownloader {          @Override         protected HttpURLConnection openConnection(final Uri uri) throws IOException {             HttpURLConnection connection = super.openConnection(uri);             connection.setRequestProperty(Constants.HEADER_X_API_KEY, "MY_API_KEY");             return connection;         }     } } 
like image 23
nhaarman Avatar answered Sep 22 '22 16:09

nhaarman