如何使用OkHttp 3.2.0在Picasso 2.5.2中添加基本身份验证 [英] How to add Basic Authentication in Picasso 2.5.2 with OkHttp 3.2.0

查看:166
本文介绍了如何使用OkHttp 3.2.0在Picasso 2.5.2中添加基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用picasso 2.5.2库从远程服务器下载位图,图像URL要求标头中具有基本身份验证.

我尝试了以下SO解析器,但是它们都无法与最新的Picasso和OkHttp库一起使用.

答案-1

答案-2

答案-3

谢谢.

解决方案

尝试使用身份验证器配置OkHttp3客户端,具体取决于您的方案和情况:

    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();

然后,使用该客户端来形成您的Picasso对象,但是使用okhttp3,您将不得不改为使用OkHttp3Downloader,如下所示:

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

您可以从> https://github.com/JakeWharton/picasso2-okhttp3-获取OkHttp3Downloader下载器

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

Thanks in advance.

解决方案

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

这篇关于如何使用OkHttp 3.2.0在Picasso 2.5.2中添加基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆