有时候要求请求服务器时向服务器发送证书,让服务器验证客户端。
要让webview能够发送ssl证书需要重写WebViewClient类,再其中写https访问替换。
需要重写shouldInterceptRequest 方法,这个方法会遍历网页中所有的网络方位,在这个方法里将需要向服务器发送ssl证书的网络访问筛选出来替换掉。网页中的很多css文件和js文件和小图标的https直接忽略证书即可。
SslPinningWebViewClient 中关于https的代码如下
public class SslPinningWebViewClient extends WebViewClient {
private LoadedListener listener;
private SSLContext sslContext;
private Context mcontext;
private WebView webView;
public SslPinningWebViewClient(Context context, LoadedListener listener,WebView webView)throws IOException {
this.listener = listener;
this.mcontext=context;
this.webView=webView;
this.sslContext= Httputil.getSSLContext(context);//此处获取ssl证书
}
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if(url.contains("mobile=1")){//此处筛选出需要向服务器发送证书的网络访问
return processRequest(Uri.parse(url));
}
return super.shouldInterceptRequest(view, url);
}
private boolean is=false;
@Override
@TargetApi(21)//api21的重写方式
public WebResourceResponse shouldInterceptRequest (final WebView view, WebResourceRequest interceptedRequest) {
if(interceptedRequest.getUrl().toString().contains("mobile=1")){//此处筛选出需要向服务器发送证书的网络访问
return processRequest(interceptedRequest.getUrl());
}
return super.shouldInterceptRequest(view, interceptedRequest);
}
//此处用来发送证书的网络请求
private WebResourceResponse processRequest(final Uri uri) {
try {
URL url = new URL(uri.toString());
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("COOKIE", Sputil.sp("erp").getString("cookie", ""));
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
InputStream is = urlConnection.getInputStream();
String contentType = urlConnection.getContentType();
String encoding = urlConnection.getContentEncoding();
if(contentType != null) {
String mimeType = contentType;
if (contentType.contains(";")) {
mimeType = contentType.split(";")[0].trim();
}
listener.Loaded(uri.toString());
return new WebResourceResponse(mimeType, encoding, is);
}
} catch (SSLHandshakeException e) {
if(isCause(CertPathValidatorException.class, e)) {
listener.PinningPreventedLoading(uri.getHost());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//将不需要发送证书的https访问验证忽略
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
}
最后在activity中给webview加上这些设置
SslPinningWebViewClient webViewClient;
try {
webViewClient = SslPinningWebViewClient(this,new LoadedListener(){
@Override
public void Loaded(String url) {
}
@Override
public void PinningPreventedLoading(String host) {
}
},webView);
}catch (IOException e){
e.printStackTrace();
}
webView.setWebViewClient(webViewClient);