The reason for this is because many times, because the background configuration of the certificate is incorrect, the app cannot access the server data, which can affect its development progress. A few lines of code, logic is clear, so the following directly paste the tool class it:
1 PackageHuolongluo.yeshen.byw.injection.model;2 3 ImportJava.security.SecureRandom;4 Importjava.security.cert.X509Certificate;5 6 ImportJavax.net.ssl.HostnameVerifier;7 ImportJavax.net.ssl.SSLContext;8 Importjavax.net.ssl.SSLSession;9 Importjavax.net.ssl.SSLSocketFactory;Ten ImportJavax.net.ssl.TrustManager; One ImportJavax.net.ssl.X509TrustManager; A - /** - * Created by fire dragon naked Mr. on 2018/1/26. the * <p> - * Ignore HTTPS certificate validation - */ - + Public classsslsocketclient - { + //get this sslsocketfactory A Public Staticsslsocketfactory getsslsocketfactory () at { - Try - { -Sslcontext Sslcontext = sslcontext.getinstance ("SSL"); -Sslcontext.init (NULL, Gettrustmanager (),Newsecurerandom ()); - returnsslcontext.getsocketfactory (); in } - Catch(Exception e) to { + Throw NewRuntimeException (e); - } the } * $ //Get TrustManagerPanax Notoginseng Private Statictrustmanager[] Gettrustmanager () - { thetrustmanager[] Trustallcerts =Newtrustmanager[]{NewX509trustmanager () + { A @Override the Public voidcheckclienttrusted (x509certificate[] chain, String authtype) + { - } $ $ @Override - Public voidcheckservertrusted (x509certificate[] chain, String authtype) - { the } - Wuyi @Override the Publicx509certificate[] Getacceptedissuers () - { Wu return Newx509certificate[]{}; - } About }}; $ returnTrustallcerts; - } - - //Get Hostnameverifier A Public Statichostnameverifier gethostnameverifier () + { theHostnameverifier Hostnameverifier =NewHostnameverifier () - { $ @Override the Public BooleanVerify (String s, sslsession sslsession) the { the return true; the } - }; in returnHostnameverifier; the } the}
With the tools class above, the "Sslsocketfactory" method and the "Hostnameverifier" method are called through the Okhttpclient.builder object. Similar to the following:
Simply:
1 builder.sslsocketfactory (Sslsocketclient.getsslsocketfactory ()); 2 Builder.hostnameverifier (Sslsocketclient.gethostnameverifier ());
Retrofit+okhttp ignoring HTTPS certificate validation