【发布时间】:2015-11-14 01:03:00
【问题描述】:
我正在尝试使用 Picasso 来在 ListView 中进行延迟图片加载。但它实际上不起作用。在我的自定义适配器中,我获取了 ImageView,初始化了一个 Picasso 对象并指示将图像加载到指定的 ImageView 中。 要从服务器检索图片,我需要提供基本身份验证,因此我创建了一个添加身份验证标头的自定义拦截器。 此外,我需要信任每个 SSL 证书,因为目前该证书尚未签名。 我面临的行为:
- 身份验证错误 --> 我已添加标题。错误消失。
- SSL 证书信任错误 --> 我添加了一个 SslSocketFactory,与我用于所有 volley 请求的相同。错误消失。
但仍然有任何图片正在加载,现在出现任何错误。
以上,构建毕加索对象的代码:
public Picasso getPicassoDownloader() throws NoSuchAlgorithmException, KeyManagementException
{
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] myTrustedAnchors = new X509Certificate[0];
return myTrustedAnchors;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
Picasso.Builder builder = new Picasso.Builder(getContext()).listener(new Listener() {
@Override
public void onImageLoadFailed(Picasso arg0, Uri arg1, Exception ex) {
ex.printStackTrace();
}
});
OkHttpClient client = new OkHttpClient();
client.setSslSocketFactory(sc.getSocketFactory());
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
});
client.networkInterceptors().add(new BasicAuthInterceptor());
Downloader downloader = new OkHttpDownloader(client);
return builder.downloader(downloader).build();
}
然后,我如何在我的适配器的 getView 方法中使用 Picasso 对象:
ImageView imageView = (ImageView) convertView.findViewById(R.id.productImage);
Picasso picasso = null;
picasso.load(produit.getImageDefaultUri()).fit().into(imageView, new Callback(){
@Override
public void onError() {
System.out.println("Error");
}
@Override
public void onSuccess() {
System.out.println("Success");
}
});
这是一个膨胀的布局,其中包含必须加载图片的 ImageView。
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/productImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:contentDescription="Product Image" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="visible"
android:indeterminateDrawable="@drawable/progressbar" >
</ProgressBar>
</RelativeLayout>
如果有人可以帮助我,那就太好了!提前致谢
【问题讨论】:
标签: android ssl picasso okhttp