我在需要获取授权来源图像的应用程序中使用通用图像加载器。
到目前为止,我已经使用自己的类扩展了URLConnectionImageDownloader类,并使用自己的实现覆盖了getStreamFromNetwork方法,该实现将URLConnection对象中的授权 header 设置为:
public class authURLConnectionImageDownloader extends URLConnectionImageDownloader {
@Override
public InputStream getStreamFromNetwork(URI imageUri) throws IOException {
String auth = Base64.encodeToString(("username" + ":"+"psswd").getBytes(), Base64.NO_WRAP);
URLConnection conn = imageUri.toURL().openConnection();
conn.setRequestProperty("Authorization", "Basic " + auth);
conn.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
conn.setReadTimeout(DEFAULT_HTTP_READ_TIMEOUT);
return new FlushedInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_SIZE));
}
并设置我的ImageLoader ...
imageLoader = ImageLoader.getInstance();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(MainActivity.this)
.imageDownloader(new authURLConnectionImageDownloader())
.build();
imageLoader.init(config);
到目前为止,我还无法使它正常工作。图像未下载。但更重要的是,我在getStreamFromNetwork()中设置了一个断点,但它从未被击中?我究竟做错了什么?
最佳答案
我是这样实现的:
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();
创建自己的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;
}
}
并将其设置为配置:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.discCacheExtraOptions(600, 600, CompressFormat.PNG, 75, null)
.imageDownloader(new AuthDownloader(getApplicationContext()))
.build();
ImageLoader.getInstance().init(config);