I am working on an example app to be able to load simple html data into a webview without distorting the content. In my Activity, I am using the org.apache.http packages to connect to a website and retrieve it's content in a private method openGoogleHomePage().
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.google.com");
get.setHeader("Content-Type", "application/x-www-form-urlencoded");
get.setHeader("User-Agent","Mozilla/5.0 (Linux;开发者_运维技巧 U; Android 2.1-update1; de-de; HTC Desire 1.19.161.5 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
HttpResponse response = client.execute(get);
String data = new BasicResponseHandler().handleResponse(response);
data = data.replaceAll("%", "%");
return data;
When I compare 'data' to the actual html content response upon opening http://www.google.com on firefox browser, the content is the same. However, when I try to load this 'data' into a webview, I don't see anything like it.
LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.main, null);
setContentView(layout);
WebView browser = (WebView) layout.findViewById(R.id.webPage);
browserSettings = browser.getSettings();
browserSettings.setJavaScriptCanOpenWindowsAutomatically(true);
browserSettings.setJavaScriptEnabled(true);
browserSettings.setSavePassword(false);
browserSettings.setSaveFormData(false);
browserSettings.setSupportZoom(false);
browser.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
String htmlData = openGoogleHomePage();
if (htmlData != null) {
browser.loadData(htmlData, "text/html", HTTP.UTF_8);
}
Whatelse do I have to change in my code to be able to view in the webview exactly as I do in the browser on a PC? On the other hand, without going through the painstaking process of invoking the URL using the http packages, and instead invoking the url from the webview using webview.loadUrl("http://www.gooogle.com") of course, retrieves the mobile version of the search-giant's page, which is way different than the PC browser version.
In short, I want to see in my webview exactly what I see on a PC browser, after handling the http invocations in my native custom code.
Also, if someone could show some pointers at handling url redirects, that would be of much help.
Some mobile device detection could be based on the user-agent. Try setting the UserAgent in the WebView to use Desktop counterpart by adding one more setting to your WebView.
browserSettings.setUserAgentString("Mozilla/5.0");
精彩评论