Encoding issue with WebView's loadData

后端 未结 8 499
星月不相逢
星月不相逢 2020-12-09 16:21

I\'m loading some data, containing latin-1 characters, in a WebView using

String uri = Uri.encode(html);
webview.loadData(uri, \"text/html\", \"ISO-8859-1\")         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 17:03

    Info from Java docs about loadData method

    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.

    The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

    Following code worked for me.

    String base64EncodedString = null;
                            try {
                                base64EncodedString = android.util.Base64.encodeToString((preString+mailContent.getBody()+postString).getBytes("UTF-8"), android.util.Base64.DEFAULT);
                            } catch (UnsupportedEncodingException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            if(base64EncodedString != null)
                            {
                                wvMailContent.loadData(base64EncodedString, "text/html; charset=utf-8", "base64");  
                            }
                            else
                            {
                                wvMailContent.loadData(preString+mailContent.getBody()+postString, "text/html; charset=utf-8", "utf-8");
    

提交回复
热议问题