【问题标题】:Android Downloading website HTML contentAndroid 下载网站 HTML 内容
【发布时间】:2016-04-11 18:15:49
【问题描述】:

您好,我正在尝试在我的 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>

【问题讨论】:

    标签: android html logging download inputstream


    【解决方案1】:

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

    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();
            }
    

    【讨论】:

      【解决方案2】:

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

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

      我怀疑您需要在将 html 写入日志之前对其进行转义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多