Glide - javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

时间:2016-12-13 06:00:13

标签: android ssl android-glide

我将服务器从HTTP迁移到HTTPS我使用了自签名证书来发送HttpUrlConnection的网络请求并且它有效但是对于图像加载它不能正常工作使用Glide进行图像加载。

  

javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:未找到证书路径的信任锚。从 https URL 加载图像通过滑动库

Glide.with(mContext).load(currentItem.getImage_path().replace(" ", "%20"))
     .listener(new RequestListener<String, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
            genericViewHolder.imageView_1.setImageResource(R.drawable.image_thumbnail);
            genericViewHolder.progressBar.setVisibility(View.GONE);
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            genericViewHolder.progressBar.setVisibility(View.GONE);
            return false;
        }
    }).into(genericViewHolder.imageView_1);

我尝试使用this链接并使用GlideModule,但它似乎不起作用。请帮忙。

5 个答案:

答案 0 :(得分:6)

问题与证书有关,请点击此链接 - https://stackoverflow.com/a/39032433/4741746

这将绕过证书并允许您进入系统

请参阅此链接 - https://futurestud.io/tutorials/glide-module-example-accepting-self-signed-https-certificates

创建您的自定义GlideModule类,OkHttpUrlLoader类并附上Glide,如上面的链接所示

你必须把

<meta-data
        android:name="io.futurestud.tutorials.glide.glidemodule.CustomImageSizeGlideModule"
        android:value="GlideModule" />

AndroidMainifiest文件https://github.com/fs-opensource/android-tutorials-glide/blob/master/app/src/main/AndroidManifest.xml

的内部应用标记

答案 1 :(得分:6)

对于Glide 4

@GlideModule
public class MyGlideModule extends AppGlideModule {

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {

        //To Attach Self Signed Ssl Certificate
        /*OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, X509TrustManager)
                .build();*/

        //Unsafe Okhttp client
        OkHttpClient okHttpClient= UnsafeHttpsClient.getUnsafeOkHttpClient();

        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
    }
}

答案 2 :(得分:3)

创建UnsafeOkHttpClient.java类

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);
    }
}
}

创建一个类MyGlideModule.java

@GlideModule
public class MyGlideModule extends AppGlideModule {
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
    OkHttpClient okHttpClient= UnsafeOkHttpClient.getUnsafeOkHttpClient();
    registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
}
}

创建一个类OkHttpStreamFetcher.java

public class OkHttpStreamFetcher implements DataFetcher<InputStream>, okhttp3.Callback {
private static final String TAG = "OkHttpFetcher";
private final Call.Factory client;
private final GlideUrl url;
private InputStream stream;
private ResponseBody responseBody;
private DataCallback<? super InputStream> callback;
private volatile Call call;

// Public API.
@SuppressWarnings("WeakerAccess")
public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
    this.client = client;
    this.url = url;
}

@Override
public void loadData(
        @NonNull Priority priority, @NonNull final DataCallback<? super InputStream> callback) {
    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();
    this.callback = callback;

    call = client.newCall(request);
    call.enqueue(this);
}

@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "OkHttp failed to obtain result", e);
    }

    callback.onLoadFailed(e);
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
    responseBody = response.body();
    if (response.isSuccessful()) {
        long contentLength = Preconditions.checkNotNull(responseBody).contentLength();
        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
        callback.onDataReady(stream);
    } else {
        callback.onLoadFailed(new HttpException(response.message(), response.code()));
    }
}

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

@Override
public void cancel() {
    Call local = call;
    if (local != null) {
        local.cancel();
    }
}

@NonNull
@Override
public Class<InputStream> getDataClass() {
    return InputStream.class;
}

@NonNull
@Override
public DataSource getDataSource() {
    return DataSource.REMOTE;
}
}

创建一个类OkHttpUrlLoader.java

public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {

private final Call.Factory client;

// Public API.
@SuppressWarnings("WeakerAccess")
public OkHttpUrlLoader(@NonNull Call.Factory client) {
    this.client = client;
}

@Override
public boolean handles(@NonNull GlideUrl url) {
    return true;
}

@Override
public LoadData<InputStream> buildLoadData(
        @NonNull GlideUrl model, int width, int height, @NonNull Options options) {
    return new LoadData<>(model, new OkHttpStreamFetcher(client, model));
}

public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
    private static volatile Call.Factory internalClient;
    private final Call.Factory client;

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

    public Factory() {
        this(getInternalClient());
    }

    public Factory(@NonNull Call.Factory client) {
        this.client = client;
    }

    @NonNull
    @Override
    public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) {
        return new OkHttpUrlLoader(client);
    }

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

添加app / build.gradle

implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
implementation("com.github.bumptech.glide:okhttp3-integration:4.2.0") {
    exclude group: 'glide-parent'
}

在AndroidManifest.xml

<application>
<meta-data
        android:name="Replace_your_package_name.UnsafeOkHttpClient"
        android:value="MyGlideModule" />
</application>

答案 3 :(得分:0)

以上两个答案都正确,但请确保也低于依赖性 添加或更改okhttp3-integration:4.4.0版本

  implementation ('com.github.bumptech.glide:okhttp3-integration:4.4.0'){
        exclude group: 'glide-parent'
    }

答案 4 :(得分:0)

我尝试使用 Glide 4.x 在 imagview 中加载 https 图像 URL。我在我的代码中应用了各种开发人员的答案,但我没有成功加载图像。最后我找到了使用 Glide 在 imageview 中加载 https 图像 URL 的解决方案。为此,您必须按照以下步骤附加带有滑行请求的证书。

步骤 1:您从 glide 官方 GitHub documentation 导入最新的 glide 库。如果您启用 proguard,则按照 glide 文档中的说明在 proguard 文件中添加代码。

Java 开发者

dependencies { 

               implementation 'com.github.bumptech.glide:glide:4.11.0' 
               annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
               implementation("com.github.bumptech.glide:okhttp3-integration:4.11.0") {
                     exclude group: 'glide-parent'
               }

             }

对于 Kotling 开发者

dependencies { 

               implementation 'com.github.bumptech.glide:glide:4.11.0' 
               kapt 'com.github.bumptech.glide:compiler:4.11.0'
               implementation("com.github.bumptech.glide:okhttp3-integration:4.11.0") {
                        exclude group: 'glide-parent'
               }

             }

第 2 步:一旦 Glide 库与您的项目成功构建。 UnsafeOkHttpClient 类。我已经在 J​​ava 中创建了这个类,但您可以根据需要在 kotlin 中创建它。

public class OkHttpStreamFetcher implements DataFetcher<InputStream>, okhttp3.Callback {
private static final String TAG = "OkHttpFetcher";
private final Call.Factory client;
private final GlideUrl url;
private InputStream stream;
private ResponseBody responseBody;
private DataFetcher.DataCallback<? super InputStream> callback;
private volatile Call call;

// Public API.
@SuppressWarnings("WeakerAccess")
public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
    this.client = client;
    this.url = url;
}

@Override
public void loadData(
        @NonNull Priority priority, @NonNull final DataCallback<? super InputStream> callback) {
    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();
    this.callback = callback;

    call = client.newCall(request);
    call.enqueue(this);
}

@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "OkHttp failed to obtain result", e);
    }

    callback.onLoadFailed(e);
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
    responseBody = response.body();
    if (response.isSuccessful()) {
        long contentLength = Preconditions.checkNotNull(responseBody).contentLength();
        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
        callback.onDataReady(stream);
    } else {
        callback.onLoadFailed(new HttpException(response.message(), response.code()));
    }
}

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

@Override
public void cancel() {
    Call local = call;
    if (local != null) {
        local.cancel();
    }
}

@NonNull
@Override
public Class<InputStream> getDataClass() {
    return InputStream.class;
}

@NonNull
@Override
public DataSource getDataSource() {
    return DataSource.REMOTE;
}  }

第 3 步:现在开始创建类,该类使用 AppGlideModule@GlideModule 注释扩展到该类。 注释后重建您的项目,它将在您的项目中创建一个 GlideApp 类。这个类帮助我们在 glide 尝试加载 https url 时发送 SSL 请求。

Java 开发人员

@GlideModule
public class MyAppGlideModule extends AppGlideModule {

     @Override
     public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
              OkHttpClient okHttpClient= UnsafeOkHttpClient.getUnsafeOkHttpClient();
              registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
    }

 }

对于 Kotlin 开发者

@GlideModule
class AppGlideModule : AppGlideModule(){
           override fun registerComponents(@NonNull context: Context, @NonNull glide: Glide, @NonNull registry: Registry) {
                      val okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient()
                      registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(okHttpClient))
            }
 }

第 4 步:使用 GlideApp,例如 GlideApp.with(this).load(imgUrl).into(glide_test_iv1)

总结: Glide 4.0 不需要在 AndroidManifest.xml 中声明“GlideModule”。您只需要执行以下步骤:

  1. YourAppGlideModule 扩展了 AppGlideModule,您可以覆盖 YourAppGlideModule 类中的函数 applyOptions。

  2. 您应该在“android studio -> build -> make project”中制作项目,它会生成 GlideApp 类。

  3. 使用 GlideApp 如 GlideApp.with(this).load(imgUrl).into(glide_test_iv1)