我想获取用户输入的网页的源代码。当他按下按钮时,他应该会在
TextView
中看到源。这是我的代码:
final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = null;
url = new URL(myEditText.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
myTextView.append(line);
}
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
}
});
当我运行它时,我在
处收到 NullPointerExceptionBufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
.-->Println 需要一条消息。
我不知道出了什么问题,因为这是来自视频教程。我已经在清单中写了
<uses-permission android:name="android.permission.INTERNET"/>
,所以一切都应该没问题。
试试这个。
url = new URL("http://www.stackoverflow.com");
如果它有效,那么您需要设置验证,例如 isValidUrl() ?
因为用户可能输入了错误的网址。
if(!TextUtils.isEmpty(myEditText.getText()))
url = new URL(myEditText.getText().toString());
else
url="";
或者如果您使用的是最新版本,请检查 StrictMode 并将其删除
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
还要检查 Android 是否有网络可用
我的解决方案是用javascript修改onPageFinished以显示html源代码。
webview1.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { /* web links should open within app, not the external browser */
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:" +
"function get_doctype() { var doctype = '<!DOCTYPE ' + document.doctype.name + (document.doctype.publicId?' PUBLIC \"' + document.doctype.publicId + '\"':'') + (document.doctype.systemId?' \"' + document.doctype.systemId + '\"':'') + '>'; return doctype; } \n" +
"" +
"var a1 = get_doctype() + document.documentElement.outerHTML; " +
" a1 = a1.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\").replaceAll(\"\\n\", \"<br>\"); " +
"" +
"var href = window.location.href;" +
"" +
"page_load = function() {" +
" window.location.href = href;" +
"};" +
"" +
"view_html = function() {" +
"$('body').html('<center><button onclick=\"page_load()\">Go To Page</button></center><pre style=\"font-weight:bold;font-size:85%;padding-left:5px;\">'+ a1 + '</pre>');" +
"};" +
"" +
"$('body').append('<span id=\"html_source_code\"></span><br><button style=\"position:absolute;bottom:0px;left:0px;z-index:800;\" onclick=\"view_html();\">View HTML Source Code</button><br>'); " +
"" +
""
);
}
});
谢谢您,请投票支持这个答案。