自己做这个之前也在网上搜了一下相关的资料,发现大多都是先发送http请求,看返回结果是否是200,如果是的话则webview.loadUrl();
后来想了想,发现这样其实就等于发送了两次请求,不合适。而且第一次请求的时候就已经获取了html界面了,为什么还要获取一遍呢?如果服务器是记录请求数量的话,这样就翻了一倍。
稍微改进了一下加载的手段,利用http去请求,获取返回code,如果是200则获取inputstream,使用webView的view.loadDataWithBaseURL("", data, "text/html",
"utf-8", "");方法加载。这样就实现了一次请求,解决400的问题了。
WebView web=new WebView(this); loadNewUrl(webpage,url); web.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // and here, if you want, you can load the page normally if (!url.startsWith("file:")) { loadNewUrl(view, url); return true; } else { return super.shouldOverrideUrlLoading(view, url); } } }); public static void loadNewUrl(final WebView view, final String url) { new Thread(new Runnable() { @Override public void run() { final HttpGet get = new HttpGet(url); HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = null; try { httpResponse = client.execute(get); int statusCode = httpResponse.getStatusLine() .getStatusCode(); if (statusCode == 500) { Log.e("TEST", "is 500 page!"); view.loadUrl("file:///android_asset/a500.html"); return; } else if (statusCode == 404) { Log.e("TEST", "is 404 page!"); view.loadUrl("file:///android_asset/a404.html"); } else if (statusCode == 200) { String data = IOHelper .fromIputStreamToString(httpResponse .getEntity().getContent()); view.loadDataWithBaseURL("", data, "text/html", "utf-8", ""); } else { } } catch (Exception e) { e.printStackTrace(); } } }).start(); }