Accessing protected images in universal image loader

懵懂的女人 提交于 2019-11-30 15:16:31
lukle

I implemented it this way:

 byte[] toEncrypt = (username + ":" + password).getBytes();
        String encryptedCredentials = Base64.encodeToString(toEncrypt, Base64.DEFAULT);
        Map<String, String> headers = new HashMap();
        headers.put("Authorization","Basic "+encryptedCredentials);

    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            ...
            .extraForDownloader(headers)
            .build();

Create your own ImageDownloader:

public class AuthDownloader extends BaseImageDownloader {

    public AuthDownloader(Context context){
        super(context);
    }

    @Override
    protected HttpURLConnection createConnection(String url, Object extra) throws IOException {
        HttpURLConnection conn = super.createConnection(url, extra);
        Map<String, String> headers = (Map<String, String>) extra;
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        return conn;
    }
}

and set it to the configuration:

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions)
            .discCacheExtraOptions(600, 600, CompressFormat.PNG, 75, null)
            .imageDownloader(new AuthDownloader(getApplicationContext()))
            .build();

    ImageLoader.getInstance().init(config);

I managed to get it working in the end...

I used the library .jar with source that comes with the example, and debugged it. I saw that it was never accessing my URLConnectionImageDownloader derived class and always using the parent.

So looked at my code, and saw I was setting up another imageloader within a previous activity that was using the default URLConnectionImageDownloader class.

Now I have created an application class and setup my ImageLoader once (as in the example app), and set the config to use my new authURLConnectionImageDownloader class. Now all my activies use this ImageLoader and it works.

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