android Glide - javax.net.ssl.SSLHandshakeException:证书路径验证器异常:找不到证书路径的信任锚

xhv8bpkk  于 2023-03-28  发布在  Android
关注(0)|答案(5)|浏览(341)

我将服务器从HTTP迁移到HTTPS,我使用自签名证书通过HttpUrlConnection发送网络请求,它工作,但对于图像加载,它不工作,因为我使用Glide进行图像加载。
javax.net.ssl.SSLHandshakeException:证书路径验证器异常:通过glide库从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,但它似乎不起作用。请帮助。

egmofgnx

egmofgnx1#

问题是关于证书,请点击此链接-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

2ic8powd

2ic8powd2#

您可以使用我从Trusting all certificates with okHttp的答案中复制的代码-
创建类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)抛出CertificateException { }

@Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String

authType)抛出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(),

内容长度);callback.onDataReady(stream);} else { callback.onLoadFailed(new HttpException(response.message(),response.code()));{\fnSimHei\bord1\shad1\pos(200,288)}

@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")

{排除组:'slide-parent' }
在安卓清单. xml中

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

hgncfbus3#

上面两个答案都正确,但也要确保下面的依赖添加或更改okhttp 3-integration:4.4.0版本

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

wvyml7n54#

滑翔机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));
    }
}
zengzsys

zengzsys5#

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

第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'
               }

             }

第二步:一旦Glide Library成功与您的项目一起构建。UnsafeOkHttpClient类。我已经在java中创建了这个类,但您可以根据需要在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));
    }

 }

对于KotlinDevloper

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

第四步:使用GlideApp,如GlideApp.with(this).load(imgUrl).into(glide_test_iv1)
**总结:**Glide 4.0不需要在AndroidManifest.xml中声明GlideModule,只需按照以下步骤操作即可:

  1. YourAppGlideModule扩展了AppGlideModule,则可以重写YourAppGlideModule类中的函数applyOptions。
    1.你应该在“android studio -〉build -〉make project”中创建项目,它将生成GlideApp类。
    1.使用GlideApp,如GlideApp.with(this).load(imgUrl).into(glide_test_iv1)

相关问题