Android下载网站HTML内容

时间:2016-04-11 18:15:49

标签: android html logging download inputstream

您好我正在尝试在Logcat中下载网站HTML内容,以便将来我可以选择具体的信息。但在我能做到之前,我想测试一下我是否可以联系该网站。目前我没有收到错误,但我也没有得到上下文。

//我创建的公共类

public class DownloadTsk extends AsyncTask<String, Void, String>{


    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {


                char current = (char) data;

                result += current;

                data = reader.read();



            }

            return result;


        } catch (MalformedURLException e) {


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


        return null;
    }
}

// Oncreate方法

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


    DownloadTsk task = new DownloadTsk();
    String result = null;

    try {
        result = task.execute("http://www.posh24.com/celebrities").get();

        Log.i("Content", result);


    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

//当前结果

 Content: <!DOCTYPE html>
          <html>
          <head>

2 个答案:

答案 0 :(得分:0)

如果您想知道您是否成功连接,那么您应该使用

int responseCode = urlConnection.getResponseCode();

实际上这就是我从HTTP请求中获取结果的方式:

int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
            con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();
        }

答案 1 :(得分:0)

您的代码可以正常工作并将页面读入字符串。

我会使用缓冲区而不是一次读取一个字符 但那是另一天的问题。

我怀疑你需要在将它写入日志之前转义html。