在Android中阅读网址的内容

use*_*565 22 android

我是android的新手,我正在试图弄清楚如何将URL的内容作为String.例如,如果我的网址是http://www.google.com/,我希望将该网页的HTML作为字符串获取.任何人都可以帮我这个吗?

Dre*_*rew 46

来自Java Docs:readingURL

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();
Run Code Online (Sandbox Code Playgroud)

而不是写每一行System.out只是将其附加到字符串.

  • 谢谢,我之前尝试过,我刚刚意识到我的问题:我忘了给它上网权限...... (3认同)
  • 如果您发布的代码示例似乎在做正确的事,则它使其他所有人都有机会找出可能导致此问题的其他原因(例如您的权限问题)。 (2认同)
  • 自API 11成为关于http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception以来的最高记录 (2认同)
  • 该代码应位于AsyncTask或任何后台线程中。 (2认同)

det*_*man 7

你可以打开一个流并读取并将每一行附加到一个字符串 - 记得用try-catch块包装所有内容 - 希望它有所帮助!

String fullString = "";
URL url = new URL("http://example.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
    fullString += line;
}
reader.close();
Run Code Online (Sandbox Code Playgroud)


liv*_*ove 5

你可以像这样把它放在一个 AsyncTask 中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    try {
        new Main2Activity.MyTask().execute(this);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static class MyTask extends AsyncTask<Object, Void, String> {

    Main2Activity activity;

    @Override
    protected String doInBackground(Object... params) {
        activity = (Main2Activity)params[0];
        try {
            StringBuilder sb = new StringBuilder();
            URL url = new URL("http://www.google.com/");

            BufferedReader in;
            in = new BufferedReader(
                    new InputStreamReader(
                            url.openStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null)
                sb.append(inputLine);

            in.close();

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String str) {
        //Do something with result string
        WebView webView = activity.findViewById(R.id.web_view);
        webView.loadData(str, "text/html; charset=UTF-8", null);
    }

}
Run Code Online (Sandbox Code Playgroud)