Android Picasso 库,如何添加身份验证标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24273783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:57:57  来源:igfitidea点击:

Android Picasso library, How to add authentication headers?

androidpicassookhttp

提问by gonzalomelov

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.

我尝试使用自定义身份验证器设置自定义 OkHttpClient,但是正如文档所说:“响应来自远程 Web 或代理服务器的身份验证挑战。” 我必须为每个图像发出 2 个请求,这并不理想。

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

有没有像 Retrofit 这样的请求拦截器?或者我在 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!

谢谢!

回答by bryant1410

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

由于 Picasso 2.5.0OkHttpDownloader类已更改,假设您使用的是 OkHttp3(因此picasso2-okhttp3-downloader),因此您必须执行以下操作:

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

来源:https: //github.com/square/picasso/issues/900

回答by nhaarman

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

有关更新的解决方案,请参阅bryant1410 的答案



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

像这样的事情可以完成设置 API 密钥标头的工作:

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;
        }
    }
}

回答by f4b

You can also add Authentication as suggested in the documentation of OkHttp

您还可以按照OkHttp 文档中的建议添加身份验证

Just add this client

只需添加此客户端

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

to Picasso like this:

像这样写给毕加索:

final Picasso picasso = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(client))
                .build();
Picasso.setSingletonInstance(picasso);

The only dependency needed is:

唯一需要的依赖是:

compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'

回答by Rakesh Ghasadiya

It's working

它正在工作

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

                   Picasso picasso = new Picasso.Builder(OnDemandImageCaptureActivity.this)
                           .downloader(new OkHttp3Downloader(okHttpClient))
                           .build();
                        picasso.load("http://example.com/abc.jpeg").into(ivcamera);

dependency:

依赖:

compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'

回答by edwardaa

A simple way like this will keep default OkHttpClient timeout and cache configurations:

像这样的简单方法将保留默认的 OkHttpClient 超时和缓存配置:

private class MyOkHttpDownloader extends OkHttpDownloader {

    public MyOkHttpDownloader(final Context context) {
        super(context);
        getClient().interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder()
                        .addHeader("X-TOKEN", "VAL")
                        .build();
                return chain.proceed(newRequest);
            }
        });
    }
}

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