在WebView中加载本地html?

我想加载一个本地的HTML到WebView没有使用“file:///”,因为这不允许cookie。 有没有办法使用像“本地主机”?

其次,我找不到在getSettings()中启用cookie的方法。 因为使用“file:///”时不允许使用cookie。

你只能做那样的事情。 这个解决scheme从一个Stringvariables中加载HTML:

String html = "<html><body>Hello, World!</body></html>"; String mime = "text/html"; String encoding = "utf-8"; WebView myWebView = (WebView)this.findViewById(R.id.myWebView); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.loadDataWithBaseURL(null, html, mime, encoding, null); 

编辑:尝试为您的需要设置loadDataWithBaseURL()的第一个参数(baseURL)

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView view = (WebView) findViewById(R.id.webView1); try { InputStream input = getResources().openRawResource(R.raw.lights); Reader is = new BufferedReader( new InputStreamReader(input, "windows-1252")); //InputStream input = getAssets().open("ws.TXT"); int size; size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); // byte buffer into a string javascrips = new String(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // String html = readFile(is); view.loadDataWithBaseURL("file:///android_res/raw/", javascrips, "text/html", "UTF-8", null); } 

试试这个代码。 这个对我有用。

 WebView mDesc = findViewById(R.id.descWv); WebSettings settings = mDesc.getSettings(); settings.setDefaultTextEncodingName("utf-8"); mDesc.loadData(mDescText, "text/html; charset=utf-8",null); 

如果要通过Android访问localhost ,则需要使用http://10.0.2.2:35643/ ,其中35643是特定的端口(如果需要)。

以下代码为我工作。

 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");