一.okhttp跳过验证写法:
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.TextView;
import com.csht.yellow.application.MyApplication;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
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;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Administrator on 2017/9/22.
*/
public class NetWorkOkhttp {
public static void getONetWorkString(String Url) {
OkHttpClient build = new OkHttpClient.Builder()
.sslSocketFactory(createSSLSocketFactory())
.hostnameVerifier(new TrustAllHostnameVerifier())
.build();
final String url = Url;//带https的网址
final Request request = new Request.Builder().url(url).build();
Call call = build.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("joker", e.getMessage());
}
@Override
public void onResponse(Call call, Response response)
throws IOException
{
}
});
}
private static class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
}
private static class TrustAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
private static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new TrustAllCerts() }, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return ssfFactory;
}
}
二.webview跳过证书验证写法:
//设置WebViewClient时,重写onReceivedSslError,在里面添加这句话handler.proceed();
webView.setWebViewClient(new WebViewClient() {
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
handler.proceed(); // 接受所有网站的证书
}
}