I am trying to create a simple Android app that will have the possibility to fetch the source code of a website. Anyways, I have written the following:
WebView webView = (WebView) findViewById(R.id.webView);
try {
webView.setWebViewClient(new WebViewClient());
InputStream input = (InputStream) new URL(url.toString()).getContent();
webView.loadDataWithBaseURL("", "<html><body><p>"+input.toString()+"</p></body></html>", "text/html", Encoding.UTF_8.toString(),"");
setContentView(webView);
} catch (Exception e) {
Alert alert = new Alert(getApplicationContext(),
"Error fetching data", e.getMessage());
}
I've tried to change the 3rd line several times to other methods that will fetch the source code, but they all redirect me to the alert (error with no message, only the title).
What am I doing wrong?
Is there a particular reason why you can't just use this to load the webpage?
webView.loadUrl("www.example.com");
If you really want to grab the source code into a string so you can manipulate it and display it as you are trying to do, try opening a stream to the content and then using standard java methods to read in the data to a String, to which you can then do whatever you want:
InputStream is = new URL("www.example.com").openStream();
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
sb.append(read);
read = br.readLine();
}
String sourceCodeString = sb.toString();
webView.loadDataWithBaseURL("www.example.com/", "<html><body><p>"+sourceCodeString+"</p></body></html>", "text/html", Encoding.UTF_8.toString(),"about:blank");