Android Picasso library, How to add authentication headers?

前端 未结 5 1102
南方客
南方客 2020-11-27 16:08

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.

5条回答
  •  独厮守ぢ
    2020-11-27 16:33

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

提交回复
热议问题