Adding Authentication Headers to NetworkImageView in Volley

≡放荡痞女 提交于 2019-12-04 04:34:55

I have come up with a solution. In order to use NetworkImageView you need to create an image loader. At this point of the code, just overide the makeImageRequest() method of ImageLoader, and inside makeImageRequest(), overide the getHeaders() method of 'ImageRequest' :

imageLoader = new ImageLoader(requestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            }) {
        @Override
        protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, final String cacheKey) {
            //return super.makeImageRequest(requestUrl, maxWidth, maxHeight, cacheKey);

            return new ImageRequest(requestUrl, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap response) {
                    onGetImageSuccess(cacheKey, response);
                }
            }, maxWidth, maxHeight,
                    Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    onGetImageError(cacheKey, error);
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("Authorization", YOUR_TOKEN);
                    return params;
                }
            };
        }
    };

This is technically one line of code :) I have tested this and it works for me.

Haven't found an easy way of doing this. I have forked Volley to accomplish what I needed. Feel free to use if you need it.

https://github.com/leofirespotter/ubervolley

Also added in here is making a rounded NetworkImageView copied from (http://solutionforandroid.blogspot.com/2013/12/rounded-networkimageview-using-volley.html)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!