使用picasso加载需要证书的https图片

我在项目中用到的图片加载框架是picasso,但是最近遇到个问题,picasso加载不出来公司的https图片,查了下需要将以下代码到application中

final OkHttpClient client = new OkHttpClient.Builder() 
.protocols(Collections.singletonList(Protocol.HTTP_1_1)) 
.build();

final Picasso picasso = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(client))
                .build();
        Picasso.setSingletonInstance(picasso);

但是加了之后还是不能加载出来,琢磨了一下可能是要加证书进行验证,因为picasso内部是okhttp进行下载的,所以查了下给okhttp设置单项证书认证,加上单项认证之后确实也就可以加载出来了,关于okhttp单向认证的问题下篇再讲。

贴一下我这边完整的代码

  HttpsUtils.SSLParams sslParams =null;
        try {
            sslParams=HttpsUtils.getSslSocketFactory(new InputStream[]{getAssets().open("ddsoucai.cer")},
                    null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient.Builder()

                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager)//https
                .build();
        final Picasso picasso = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(client))
                .build();
        Picasso.setSingletonInstance(picasso);

至于上面代码中的HttpsUtils是一个单向认证的工具类。其中的OkHttp3Downloader是特意为picasso写的加载https图片所做的一个类OkHttp3Downloader

你可能感兴趣的:(android)