在okhttp3,WebView中忽略HTTPS证书校验

Posted 土豆吞噬者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在okhttp3,WebView中忽略HTTPS证书校验相关的知识,希望对你有一定的参考价值。

在APP开发过程中,后台使用的可能是自签的Https证书,如果不忽略证书校验,会出现Trust anchor for certification path not found的错误

Okhttp3忽略HTTPS证书校验

import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLSocketClient {

    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
}
sClient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
        .build();

WebView忽略HTTPS证书校验

        wv.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//忽略证书错误继续加载页面
            }
        });
技术分享图片

以上是关于在okhttp3,WebView中忽略HTTPS证书校验的主要内容,如果未能解决你的问题,请参考以下文章

okhttp3.0忽略https证书

[如何在Webview和Retrofit2 Okhttp3之间共享cookie

Android WebView 似乎忽略了网页上的“视口”信息

Android WebView 在添加 WebViewClient 时忽略 target="_blank"

Android WebView 样式背景颜色:在 android 2.2 上忽略透明

Glide3.0加载https图片