在Android中阅读网址的内容

时间:2010-01-16 01:25:54

标签: android

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

3 个答案:

答案 0 :(得分:45)

来自Java文档: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();

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

答案 1 :(得分:6)

你可以打开一个流并读取并将每一行附加到一个字符串 - 记得用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();

答案 2 :(得分:3)

你可以把它放在像这样的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);
    }

}