【问题标题】:Android get web page sourceAndroid获取网页源
【发布时间】:2012-09-27 09:10:21
【问题描述】:

我想获取用户输入的网页的源代码。当他按下按钮时,他应该在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());
                }

            }
        });

当我运行它时,我在

处得到一个 NullPointerException
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

.-->Println 需要一条消息。

我不知道出了什么问题,因为这是来自视频教程。我已经在 Manifest 中写了<uses-permission android:name="android.permission.INTERNET"/>,所以一切都会好起来的。

【问题讨论】:

  • 我怀疑您的网址为空。是否需要在 EditText 中,您可以验证它的值吗?

标签: android url web


【解决方案1】:

试试这个。

url = new URL("http://www.stackoverflow.com");

如果它有效,那么您需要为 isValidUrl() 设置验证?

因为用户可能输入了错误的 URL。

【讨论】:

  • 我如何获得网页的一些 html 源代码?如果我得到完整的源页面,它可能会花很多时间,而且我不需要所有线路,你能帮我吗?非常感谢
【解决方案2】:
    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 是否有网络可用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多