Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Basic Authentication in Picasso 2.5.2 with OkHttp 3.2.0

I am using picasso 2.5.2 library to download bitmap from remote server, the image url requires basic authentication in header.

i have tried the following SO ansers but none of them work with the latest picasso and OkHttp libraries.

Answer - 1

Answer - 2

Answer - 3

enter image description here

Thanks in advance.

like image 581
darwin Avatar asked Apr 22 '16 06:04

darwin


1 Answers

Try configuring an OkHttp3 client with authenticator, depending on your scheme and situation:

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .authenticator(new Authenticator()
                {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException
                    {
                        String credential = Credentials.basic("user", "pass");
                        return response.request().newBuilder()
                                .header("Authorization", credential)
                                .build();
                    }
                })
            .build();

Then, use that client in forming your Picasso object, but with okhttp3 you will have to use a OkHttp3Downloader instead, like so:

    Picasso picasso = new Picasso.Builder(context)
        .downloader(new OkHttp3Downloader(okHttpClient))
        .build();

You can get the OkHttp3Downloader from https://github.com/JakeWharton/picasso2-okhttp3-downloader

like image 193
Flavius Avatar answered Oct 27 '22 00:10

Flavius