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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With