Как загрузить изображение в глайд с https незащищенным сертификатом - PullRequest
0 голосов
/ 23 октября 2018

Я пытаюсь загрузить изображение в Glide, в localhost оно будет загружаться идеально, когда я перехожу на сервер, оно не загружает, как решить эту проблему.

код:

Glide.with(mContext)
                .load(https://www.server9host.com/ocean/oceans/dashboard/nature.jpg)
                .placeholder(R.drawable.defgall)
                .error(R.drawable.defgall)
                .override(200, 200)
                .into(myHolder.onlineimage);

1 Ответ

0 голосов
/ 23 октября 2018

Создайте этот класс.

    public class UnsafeOkHttpGlideModule implements GlideModule {
        @Override
        public void applyOptions(Context context, GlideBuilder builder) {

        }

        @Override
        public void registerComponents(Context context, Glide glide) {
            OkHttpClient client = UnsafeOkHttpClient.getUnsafeOkHttpClient();
            glide.register(GlideUrl.class, InputStream.class,
                    new OkHttpUrlLoader.Factory(client));
        }
    }

        public class UnsafeOkHttpClient {
            public static OkHttpClient getUnsafeOkHttpClient() {
                try {
                    // Create a trust manager that does not validate certificate chains
                    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[]{};
                                }
                            }
                    };

                    // Install the all-trusting trust manager
                    final SSLContext sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

                    // Create an ssl socket factory with our all-trusting manager
                    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;
                        }
                    });

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

    public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
        public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
            private static volatile OkHttpClient internalClient;
            private OkHttpClient client;

            private static OkHttpClient getInternalClient() {
                if (internalClient == null) {
                    synchronized (Factory.class) {
                        if (internalClient == null) {
                            internalClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();
                        }
                    }
                }
                return internalClient;
            }

            /**
             * Constructor for a new Factory that runs requests using a static singleton client.
             */
            public Factory() {
                this(getInternalClient());
            }

            /**
             * Constructor for a new Factory that runs requests using given client.
             */
            public Factory(OkHttpClient client) {
                this.client = client;
            }

            @Override
            public ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {
                return new OkHttpUrlLoader(client);
            }

            @Override
            public void teardown() {
                // Do nothing, this instance doesn't own the client.
            }
        }

        private final OkHttpClient client;

        public OkHttpUrlLoader(OkHttpClient client) {
            this.client = client;
        }

        @Override
        public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
            return new OkHttpStreamFetcher(client, model);
        }
    }

public class OkHttpStreamFetcher implements DataFetcher<InputStream> {
    private final OkHttpClient client;
    private final GlideUrl url;
    private InputStream stream;
    private ResponseBody responseBody;

    public OkHttpStreamFetcher(OkHttpClient client, GlideUrl url) {
        this.client = client;
        this.url = url;
    }

    @Override
    public InputStream loadData(Priority priority) throws Exception {
        Request.Builder requestBuilder = new Request.Builder()
                .url(url.toStringUrl());

        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
            String key = headerEntry.getKey();
            requestBuilder.addHeader(key, headerEntry.getValue());
        }

        Request request = requestBuilder.build();

        Response response = client.newCall(request).execute();
        responseBody = response.body();
        if (!response.isSuccessful()) {
            throw new IOException("Request failed with code: " + response.code());
        }

        long contentLength = responseBody.contentLength();
        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
        return stream;
    }

    @Override
    public void cleanup() {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // Ignored
            }
        }
        if (responseBody != null) {
            responseBody.close();
        }
    }

    @Override
    public String getId() {
        return url.getCacheKey();
    }

    @Override
    public void cancel() {
        // TODO: call cancel on the client when this method is called on a background thread. See #257
    }
}

и используйте этот код где угодно

Glide.with(context).load(imageUrl).into(imageView);
...