今天遇到一个奇怪的问题。
我使用WebView加载一个网页。
方法1. 直接使用 loadUrl() 方法,没有问题。完全可以。方法2. 使用loadData()方法,出现问题,无法显示。
方法3. 使用loadDataWithBaseURL()方法, 完全可以。
--------------------------------------------------------------------------------------------
我就纳闷了,为什么唯独 webView.loadData()这个方法出错呢?
要知道,WebView是无法捕捉到401、404这样的错误的,只能捕捉到网络超时等这些错误。 所以为了可以判断服务器的相应,我需要HttpConnection来判断返回码, 先从网页上将数据拉下来,然后再通过loadData显示。 恩,不错的想法.. (当然用loadDataWithBaseURL也可以实现了,但是我还是想知道为什么loadData不可以。)
可是.. 现实有点残酷... 显示不了,NND!
看了下官方文档..
public void loadData (String data, String mimeType, String encoding) Since: API Level 1 Load the given data into the WebView. This will load the data into WebView using the data: scheme. Content loaded through this mechanism does not have the ability to load content from the network. Parameters data A String of data in the given encoding. The date must be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively. mimeType The MIMEType of the data. i.e. text/html, image/jpeg encoding The encoding of the data. i.e. utf-8, base64 public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl) Since: API Level 1 Load the given data into the WebView, use the provided URL as the base URL for the content. The base URL is the URL that represents the page that is loaded through this interface. As such, it is used to resolve any relative URLs. The historyUrl is used for the history entry. Note for post 1.0. Due to the change in the WebKit, the access to asset files through "file:///android_asset/" for the sub resources is more restricted. If you provide null or empty string as baseUrl, you won't be able to access asset files. If the baseUrl is anything other than http(s)/ftp(s)/about/javascript as scheme, you can access asset files for sub resources. Parameters baseUrl Url to resolve relative paths with, if null defaults to "about:blank" data A String of data in the given encoding. mimeType The MIMEType of the data. i.e. text/html. If null, defaults to "text/html" encoding The encoding of the data. i.e. utf-8, us-ascii historyUrl URL to use as the history entry. Can be null.终于发现区别了。 原来loadData的第一个参数中,不能有特殊字符“#”,“%”,“\”, “?”.必须将其转化为%23,%25,%27,%3f.
而loadDataWithBaseURL 却没这个要求。
我了个去,这是何苦呢? 为什么要这样设计呢?
下面解决一下这个问题。 用encode方法转一下即可。