Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Authentication Headers to NetworkImageView in Volley

I use Volley and NetworkImageView. This has been working great for several projects. However I need to send auth token in headers for my image request right now. What is the best way to do this? In my normal requests I override getHeaders() and put my token in that way. But ImageLoader which is what NetworkImageView uses generates a generic Request, making it hard to add headers...

like image 947
Leo Avatar asked Mar 21 '14 20:03

Leo


1 Answers

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.

like image 89
Siavash Avatar answered Oct 31 '22 07:10

Siavash