Picasso不支持下载使用https协议的图像

时间:2014-05-09 10:52:28

标签: android picasso

您好我正在使用Picasso库从URL下载图片。

网址:https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t1.0-1/s200x200/1472865_191408954385576_14109897_n.jpg

网址是使用https协议,在这里我无法使用Picasso下载https协议的图像。

它不支持下载使用https协议的图像,只有在我使用http proctocol的情况下它才适用于我吗?

这里我试图获取使用https协议的位图

com.squareup.picasso.Target target = new com.squareup.picasso.Target() {

@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom loadedFrom) {
    userProfile.setBitmap(bitmap);
    // call the Web API to register the walker here
    new AudioStreetAsyncTask(getActivity(), userProfile, getString(R.string.registration_processing_message), new TaskCompleteListener() {
        @Override
        public void onTaskCompleted(String jsonResponse) {
           Log.d(TAG, jsonResponse);
        }
    });
}

@Override
public void onBitmapFailed(Drawable drawable) {
    userProfile.setBitmap(null);
    // call the Web API to register the walker here
    new AudioStreetAsyncTask(getActivity(), userProfile, getString(R.string.registration_processing_message), new TaskCompleteListener() {
        @Override
        public void onTaskCompleted(String jsonResponse) {
           Log.d(TAG, jsonResponse);
        }
    }).execute();
}

@Override
public void onPrepareLoad(Drawable drawable) {}
};

Picasso.with(getActivity()).load(imgUrl.toString()).into(target);

有什么想法吗?

5 个答案:

答案 0 :(得分:34)

Gradle

中使用这些依赖项
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
compile 'com.squareup.picasso:picasso:2.4.0'

这个类而不是原来的Picasso

毕加索班:

 public class PicassoTrustAll {

    private static Picasso mInstance = null;

    private PicassoTrustAll(Context context) {
        OkHttpClient client = new OkHttpClient();
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            client.setSslSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mInstance = new Picasso.Builder(context)
                .downloader(new OkHttpDownloader(client))
                .listener(new Picasso.Listener() {
                    @Override
                    public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                        Log.e("PICASSO", exception);
                    }
                }).build();

    }

    public static Picasso getInstance(Context context) {
        if (mInstance == null) {
             new PicassoTrustAll(context);
        }
        return mInstance;
    }
}

用法示例:

PicassoTrustAll.getInstance(context)
                .load(url)
                .into(imageView);

答案 1 :(得分:3)

@ nexus700120解决方案不是最新的

@Neha Tyagi解决方案有效但在每个活动实例中创建多个Picasso实例,这会泄漏内存

所以我精心设计了一个用于重定向图像网址的最新单例解决方案 -

CustomPicasso.java

import android.content.Context;
import android.util.Log;

import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;

/**
 * Created by Hrishikesh Kadam on 19/12/2017
 */

public class CustomPicasso {

    private static String LOG_TAG = CustomPicasso.class.getSimpleName();
    private static boolean hasCustomPicassoSingletonInstanceSet;

    public static Picasso with(Context context) {

        if (hasCustomPicassoSingletonInstanceSet)
            return Picasso.with(context);

        try {
            Picasso.setSingletonInstance(null);
        } catch (IllegalStateException e) {
            Log.w(LOG_TAG, "-> Default singleton instance already present" +
                    " so CustomPicasso singleton cannot be set. Use CustomPicasso.getNewInstance() now.");
            return Picasso.with(context);
        }

        Picasso picasso = new Picasso.Builder(context).
                downloader(new OkHttp3Downloader(context))
                .build();

        Picasso.setSingletonInstance(picasso);
        Log.w(LOG_TAG, "-> CustomPicasso singleton set to Picasso singleton." +
                " In case if you need Picasso singleton in future then use Picasso.Builder()");
        hasCustomPicassoSingletonInstanceSet = true;

        return picasso;
    }

    public static Picasso getNewInstance(Context context) {

        Log.w(LOG_TAG, "-> Do not forget to call customPicasso.shutdown()" +
                " to avoid memory leak");

        return new Picasso.Builder(context).
                downloader(new OkHttp3Downloader(context))
                .build();
    }
}

build.gradle(Module:app)

android {

    ...

}

dependencies {

    ...

    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}

用法 -

CustomPicasso.with(context)
    .load("http://i.imgur.com/DvpvklR.png")
    .into(imageView);

有关最新版本,请查看CustomPicasso要点 - https://gist.github.com/hrishikesh-kadam/09cef31c736de088313f1a102f5ed3a3

答案 2 :(得分:2)

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

            Picasso picasso = new Picasso.Builder(mContext)
                    .downloader(new OkHttp3Downloader(client))
                    .build();
picasso .with(mContext).load(YOUR_URL).into(YOUR_IMAGEVIEW);

添加

compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'

答案 3 :(得分:1)

只需将此代码放入您的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);

从此link进行检查。

答案 4 :(得分:0)

以下对于这些依赖项工作正常:

implementation 'com.squareup.okhttp3:okhttp:3.0.1'
implementation 'com.squareup.picasso:picasso:2.71828'

首先定义一个接受证书的客户端:

public class SelfSignCertHttpClient {
    public static OkHttpClient getSelfSignOkHttpClient(List<Interceptor> interceptors) {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

来源:https://futurestud.io/tutorials/retrofit-2-how-to-trust-unsafe-ssl-certificates-self-signed-expired

我还添加了在创建客户端时传递拦截器列表的选项。

您可以定义一个PicasoTrustAll类:

public class PicassoTrustAll {

    private static Picasso mInstance = null;

    private PicassoTrustAll(Context context) {
        List<Interceptor> interceptors = new ArrayList<>();
        // Add any interceptors you wish (e.g Authorization Header interceptor)

        mInstance = new Picasso.Builder(context)
                .downloader(new OkHttp3Downloader(SelfSignCertHttpClient.getSelfSignOkHttpClient(interceptors)))
                .listener((picasso, uri, exception) -> Log.e("PICASSO", exception.getMessage())).build();

    }

    public static Picasso getInstance(Context context) {
        if (mInstance == null) {
            new PicassoTrustAll(context);
        }
        return mInstance;
    }
}

样品用量:

PicassoTrustAll.getInstance(this).load("https://10.0.2.2/path/to/picture").into(mainPictureView);