Android:下载.html并将其转换为String

use*_*568 2 html java string parsing android

我需要从某个URL下载.html文件.我该怎么做?我怎样才能将它转换为String?

更新:

我不知道为什么你downvoting.我只能使用一种方法在iOS上获得所需的结果stringWithContentsOfURL:encoding:error:.我建议Android有类似的.方法

use*_*568 5

下面的代码从链接下载html页面,并在完成回调中返回转换为字符串的html页面

public class HTMLPageDownloader extends AsyncTask<Void, Void, String> {
    public static interface HTMLPageDownloaderListener {
        public abstract void completionCallBack(String html);
    }
    public HTMLPageDownloaderListener listener;
    public String link;
    public HTMLPageDownloader (String aLink, HTMLPageDownloaderListener aListener) {
        listener = aListener;
        link = aLink;
    }

    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(link);
        String html = "";
        try {
            HttpResponse response = client.execute(request);
            InputStream in;
            in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
            in.close();
            html = str.toString();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return html;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (!isCancelled()) {
            listener.completionCallBack(result);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)