PSA: Using Picasso with a custom downloader

Picasso is an awesome library for downloading and caching images.  If the images that you need to download require authentication you can do that by specifying a custom Downloader class. If you do this you can no longer use the with method to initialise Picasso.

This is explained if you read the javadocs but if you’re like me you may have been stumped for a short while because it looked like your custom downloader was not working. In my case I needed to add a bearer authentication header to the image request so I did this:

Picasso.Builder builder = new Picasso.Builder(getContext());

builder.downloader(new OkHttpDownloader(getContext()) {
    @Override
    protected HttpURLConnection openConnection(Uri uri) throws IOException {
        HttpURLConnection connection = super.openConnection(uri);
        connection.addRequestProperty("Authorization", "Bearer: <token>");
        return connection;
    }
});

Once you have done this you can use Picasso as normal, but don’t use the with method or that will undo the changes you have made.

 

builder.build()
        .load(Uri.parse("https://example.com/image.png"))
        .into(imageView);

One thought on “PSA: Using Picasso with a custom downloader

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s