Android WebView with https loadUrl shows blank/empty page
2012-10-10 08:19
651 查看
AndroidWebViewwithhttpsloadUrlshowsblank/emptypage
September28,2010
IrecentlyencounteredthisproblemwhiletryingtodevelopaWebViewthatissupportedonDoughnut(1.6)andabove.WhenpresentedwithahttpsurltheWebViewjustrendersablankpage.ItseemsthatuntilFroyo,Androiddidn’tprovideapublicAPItoletyoumanuallydecideifyouwantedtoproceedtoanuntrustedwebsiteviaaWebView.
Notethatinthiscaseitisnoteventhatthewebsitewasuntrusted(intheconventionalsense)–itisbecauseThawteisnotinthedefaultlistoftrustedcertificateauthoritiesonAndroid.IfyouusethestandardwebbrowseronAndroid,thebrowser
presentsatypicalwarningdialog(aspresentedbelow)thatenablesyoutoacceptthecertificateandcarryon.
IfyouareusingFroyoasthetargetSDKthenyoucanuse:
1 | engine =(WebView)findViewById(R.id.my_webview); |
2 | engine.setWebViewClient( new WebViewClient() { |
3 | public void onReceivedSslError |
4 | handler.proceed() ; |
5 | } |
6 | } |
a)interceptallpagerequestsandforwardtoexternalwebbrowserifurlbeginswithhttps(notacleanorniceuserexperienceandtotallyunnecessaryforFroyoandabove)
b)addcertificateofwebsitetolocalkeystore(inthiscaseIamservingmultiplewebpagesandtheoriginofmanyoftheseisnotknownuntilruntime)
c)makeFroyotheminSDKanddiscardpreviousversionsofAndroid(notasuitableoption)
d)hackandusesomeprivateapis(theoptiondescribedbelow)
Tosolvethisproblemwehavetouseaprivateinterface(notpublishedonSDKbutpresentinrealSDKruntime).AsyoucanseeintheAndroidsrctree,the
indeedpresent(andused–itsimplycancelstherequest)inDoughnut.However,thismethodisnotpresentedtousintheSDK-itishiddenbecauseitcontainsaparametertypeSslErrorwhichislocatedinahiddenpackage.Therefore,weneedtocopythese
srcfilesintoourprojectsothatwecanaccessthem:
1)Copy
withinyoursrcfolder.
2)Copy
withinyoursrcfolder.
3)SincewereplicatedthepathstothesrcfilesintheSDK,ourcodetooverrideonSslErrorabovenowworksonAndroid1.6.
Caution:bearinmindthatweareusingaprivateAPIandGooglereservetherighttochangeprivateAPIsatanytime–thoughinthiscaseitisunlikelysincethey’venowmadethisavailableinFroyo.
Sharethis:
Likethis:
Onebloggerlikesthis.
Postedbydamianflannery
Filedin
Tags:
api,
20
Comments»
20Responsesto“AndroidWebViewwithhttpsloadUrlshowsblank/emptypage”
BanoSays:
September29,2010at9:34
am
Hi,Ihaveusedthismethodandothermethod(likethis
andIcan’tseeahttpspageintheWebView.Canyouhelpme?
September29,2010at9:42
am
Icantry.Yourrequestforhelpisabitvaguethough…
BanoSays:
September29,2010at10:26
pm
Sorry,Idid’tknowifIshouldwritealargepost.MyproblemiswiththeHttpPostconnections,Icreatean“DefaultHttpClient”anda“HttpPost”,nextIcreatealistofvaluestosendandfinallyexecuteit.
Thisworkinhttpconections,butinhttpsconectionsItrythemethodsIfindonInternetanddon’tgetittowork(Getnottrustedcertificate).
Thelastcode(withcustomSSLShocketFactoryandTrustManager):
try{
////
SchemeRegistryschemeRegistry=newSchemeRegistry();
schemeRegistry.register(newScheme(“https”,newEasySSLSocketFactory(),443));
HttpParamsparams=newBasicHttpParams();
SingleClientConnManagermgr=newSingleClientConnManager(params,schemeRegistry);
DefaultHttpClienthc=newDefaultHttpClient(mgr,params);
///
//DefaultHttpClienthc=newDefaultHttpClient();
ResponseHandlerres=newBasicResponseHandler();
HttpPostpostMethod=newHttpPost(DIRECCION);
ListnameValuePairs=newArrayList(3);
nameValuePairs.add(newBasicNameValuePair(“usuario”,nom));
nameValuePairs.add(newBasicNameValuePair(“tipo_firma”,tip));
nameValuePairs.add(newBasicNameValuePair(“string_img”,img));
postMethod.setEntity(newUrlEncodedFormEntity(nameValuePairs));
Stringresponse=hc.execute(postMethod,res);
returnresponse;
}catch(ClientProtocolExceptione){
pasos=“Excepción:”+e.toString();
}catch(IOExceptione){
//“Error1:Unabletoestablishcommunicationwiththeserver.Checkyourconfiguration.”
pasos=pasos+“Excepción:”+e.toString();
}
ifyoucanhelpme,itwouldveryhelpfull.
PD:Sorryformybadenglish…
September30,2010at7:33
am
Thebestwaywouldbetoaddtheserver’spubliccertificatetoyourAndroidApp’strustedstore:
Otherwiseyoucouldsimplystopcheckingallhostsfortheircertificate:
BanoSays:
September30,2010at9:39
am
Finally,yourpostgivemeanidea.IchangetheDefaultHttpClientforHttpsURLConection,usingOutputStreamandInputStreamtothecomunication.NextIapplythesecondlinkyougiveme(Ivisitedityetbutdidn’thelpmeinmypreviouslyidea).
Ican’tusetheSSLcertificatecreatorbecauseIhaven’tdirectaccesstotheserveroftheproyect.
thecodeofSend:
try{
////
Stringlocation=“usuario=”+nom+“&tipo_firma=”+tip+“&string_img=”+img;
URLurl=newURL(DIRECCION);
trustAllHosts();
HttpsURLConnectionhttps=(HttpsURLConnection)url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
https.setRequestMethod(“POST”);
https.setDoOutput(true);
https.setUseCaches(false);
https.setRequestProperty(“Content-Type”,
“application/x-www-form-urlencoded”);
https.connect();
OutputStreamost=https.getOutputStream();
DataOutputStreamout=newDataOutputStream(ost);
out.writeBytes(location);
out.flush();
ost=null;
InputStreamist=https.getInputStream();
BufferedReaderin=newBufferedReader(newInputStreamReader(ist));
StringBuffersb=newStringBuffer();
char[]c=newchar[1];
while(in.read(c,0,1)==1){
sb.append(c[0]);
}
Stringresponse=sb.toString();
///
returnresponse;
}catch(ClientProtocolExceptione){
pasos=“Excepción:”+e.toString();
}catch(IOExceptione){
//“Error1:Unabletoestablishcommunicationwiththeserver.Checkyourconfiguration.”
pasos=pasos+“Excepción:”+e.toString();
}
Nextaddingthetrustpart:
//alwaysverifythehost–dontcheckforcertificate
finalstaticHostnameVerifierDO_NOT_VERIFY=newHostnameVerifier(){
publicbooleanverify(Stringhostname,SSLSessionsession){
returntrue;
}
};
/**
*Trusteveryserver–dontcheckforanycertificate
*/
privatestaticvoidtrustAllHosts(){
//Createatrustmanagerthatdoesnotvalidatecertificatechains
TrustManager[]trustAllCerts=newTrustManager[]{newX509TrustManager(){
publicjava.security.cert.X509Certificate[]getAcceptedIssuers(){
returnnewjava.security.cert.X509Certificate[]{};
}
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{}
publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{}
}};
//Installtheall-trustingtrustmanager
try{
SSLContextsc=SSLContext.getInstance(“TLS”);
sc.init(null,trustAllCerts,newjava.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}catch(Exceptione){
e.printStackTrace();
}
}
Thanksforyourhelp.
You’rewelcome
Vito
AndoliniSays:
January12,2012at9:41
pm
CrazyBob’sarticleisasolutionforSSLissueswiththeHttpClient,notwithaWebView.Idon’tbelieveyoucanaddacertificatetotheapp’strustedstoreandhavethatusedbyaWebView.
Hi,
Justwantedtothankyoutohaveresolvedmyproblemin2seconds.
Workingoneclair2.1atthemomentIhadexactlythesameissueyoudescribed.Yourfixedavoidedmealotoftroubles.
thanks
William
AnsariSays:
December27,2010at4:55
am
Thanksalot,theabovesolutionworks.
Sebastian
BSays:
February23,2011at2:38
pm
Thankyouverymuch,thisisexcellent!!!
IhadbeenstrugglingwiththisforsomehoursbeforeIfoundyoursolution.
Artem
RussakovskiiSays:
Thanks,washavingthesameprobleminaprojecttargetingAndroid1.6.NowIknowwhattheheckisgoingon.
[...]WebViewjustswallowedthiswithnoerrormessages,butabitofgooglingandfoundthefollowingblogpostabouthowtoworkroundthecertificatemissmatchandevenhowtomakeitworkwithAndroid[...]
HiAll,
IamtryingtoretrievePOSTparameterfromResponse.butnotablegetitfromandroidWebview.
CouldanyonehelpmeorgiveanideatoretrievePOSTdatafromresponseURL.
Thanks&Regards
Idon’tthinkwebviewisveryconduciveforthatkindofthingbutthelinkbelowmighthelp.
RichardSays:
IhaveappliedyourtrickanditworksfineuntilIrunonarealAndroiddevice1.6or2.1.ThentheoverloadingofclassesisstopbytheDEXloader!!!anytrickstogetaround?
RichardSays:
August15,2011at10:05
am
08-1512:03:41.938:DEBUG/dalvikvm(3003):DexOpt:‘Landroid/net/http/SslError;’hasanearlierdefinition;blockingout
08-1512:03:41.938:DEBUG/dalvikvm(3003):DexOpt:‘Landroid/webkit/WebViewClient;’hasanearlierdefinition;blockingout
08-1512:03:41.973:DEBUG/dalvikvm(3003):DexOpt:notverifying‘Landroid/net/http/SslError;’:multipledefinitions
08-1512:03:41.973:DEBUG/dalvikvm(3003):DexOpt:notverifying‘Landroid/webkit/WebViewClient;’:multipledefinitions
08-1512:03:42.153:INFO/dalvikvm(3003):DexOpt:notresolvingambiguousclass‘Landroid/webkit/WebViewClient;’
HiDamian,
I’vebeenstrugglingacoupleofnightsgettingpostUrltoworkwhenpostingtoahttpssite.ItriedtouseallsortsofTrustedManagersetcetcbutwithnoluck.
ThenIfoundthisgemofyours,readitandinlessthan10minutesIwasup’nrunning.
Ibowmyheadinhumblesubmission.
Thankyou.
/brian
January11,2012at12:28
am
Hello,Damianthnxforthetutorialbutistilldontmanagetogetitwork.maybifuhavesometimeucanhelpmeloadhttpsinmywebview
packagehere.testing.a.cool.app;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.Window;
importandroid.webkit.WebChromeClient;
importandroid.webkit.WebView;
importandroid.webkit.WebViewClient;
publicclassWebPageLoaderextendsActivity
{
finalActivityactivity=this;
@Override
publicvoidonCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebViewwebView=(WebView)findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(newWebChromeClient(){
publicvoidonProgressChanged(WebViewview,intprogress)
{
activity.setTitle(“Grabbingthebitsandthebytes..”);
activity.setProgress(progress*100);
if(progress==100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(newWebViewClient(){
@Override
publicvoidonReceivedError(WebViewview,interrorCode,Stringdescription,StringfailingUrl)
{
//Handletheerror
}
@Override
publicbooleanshouldOverrideUrlLoading(WebViewview,Stringurl)
{
view.loadUrl(url);
returntrue;
}
});
webView.loadUrl(“https://website.willnot.open”);
}
}
ArthurSays:
January17,2012at1:40
pm
Thanksalot!!!!
becomingthebeastSays:
GreatpostDamian.
Asalwaysyourarticlesaremostuseful.
Thankyou!
相关文章推荐
- [Android] WebView之loadDataWithBaseUrl()和loadUrl()
- Android中的WebView之loadDataWithBaseURL遇到的坑
- Android如何使用WebView访问https的网站
- Android webview 加载https网页显示空白
- Android - WebView 加载 Https 出现 SSL Error. Failed to validate the certificate chain
- android webview 访问https页面 SslError 处理
- Android 7.0系统webview 显示https页面空白处理
- Android如何使用WebView访问https的网站
- Android WebView打开https地址错误的问题
- Android如何使用WebView访问https的网站
- Android之WebView——解决加载Https以及根据网页动态设置WebView高度等难题
- Android-webView的loadUrl
- Android开发WebView加载自签名认证的https网址
- Android webview loadUrl() 禁止弹出系统浏览器代码
- Android 7.0系统webview 显示https页面空白处理方法
- android webview加载https网站
- Magento shows blank/empty page. How do I solve this?
- 【Android】WebView加载https页面不能正常显示资源问题
- android webview & httpclient 处理 ssl (https)验证
- android webview 加载https