您的位置:首页 > 移动开发 > Android开发

【Android】loadData与loadDataWithBaseURL的区别

2013-06-16 02:39 681 查看

public void loadData(String data,String
mimeType,String encoding)

Added in
API level 1

Loads the given data into this WebView using a 'data' scheme URL.

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use
loadDataWithBaseURL()

with an appropriate base URL.

The encoding parameter specifies whether the data is base64 or URL encoded. If the data is base64 encoded, the value of the encoding parameter must be 'base64'. For all other values of the parameter, including null, it is assumed that the data uses ASCII
encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.Parameters

dataa String of data in the given encoding
mimeTypethe MIME type of the data, e.g. 'text/html'
encodingthe encoding of the data
使用'data'格式的URL来将制定的数据加载到WebView中。

要注意,如果使用任何非‘data’格式,包括‘http(s)’作为scheme,在页面中运行的js将不能被访问到内容;

为了避免这一点,采用一个合适的base URL来调用
loadDataWithBaseURL()

是以个好的选择;

encoding指定了数据是否是base64或者URL编码。如果数据时base64编码,参数的值必须是“base64”。

对于任何其它的参数,包括null,系统会默认使用ascll码来编码URL。。。

例如'#', '%', '\', '?'必须分别被替换为%23, %25, %27, %3f

public void loadDataWithBaseURL(String baseUrl,String
data,String mimeType,String encoding,String
historyUrl)

Added in
API level 1

Loads the given data into this WebView, using baseUrl as the base URL for the content. The base URL is used both to resolve relative URLs and when applying JavaScript's same origin policy. The historyUrl is used for the history entry.

Parameters

baseUrlthe URL to use as the page's base URL. If null defaults to 'about:blank'.
dataa String of data in the given encoding
mimeTypethe MIMEType of the data, e.g. 'text/html'. If null, defaults to 'text/html'.
encodingthe encoding of the data
historyUrlthe URL to use as the history entry. If null defaults to 'about:blank'.
将制定内容加载到WebView中,使用baseURl作为内容中的基地址。

这个baseUrl 不仅用于相对URL,而且也用于js的根地址。historyUrl用与指向历史记录(这个需要我们自己实现,其实就是个地址)。

需要注意的就是history所指向的必须是一个页面,并且页面存在于SD卡中或程序中(assets),loadDataWithBaseURL,它本身并不会向历史记录中存储数据,要想实现历史记录,需要我们自己来实现,也许是我的技术有限,我有了比较笨的访求来实现:就是在加载页面时,我把数据另外的写到一个html页面中,并把它保存到assest中,当点击返回时,它会通过historyUrl指向的路径来加载页面,这样就解决了历史记录问题。

上面这两种方法,我建议使用后者,虽然loadData的历史记录不需要我们自己来实现,但在使用时,我们必须把所有的%,#,\,?转换掉,而且不支持中文。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: