使用HttpUrlConnetion读取html页面,因为不知道html的编码,第一次按默认编码读取到一个字符串中,然后再根据该字符串获得html的字符编码,再使用该字符编码再次读取,但是这里的输入流(connection.getInputStream());)在第一个while处已经读到末尾了,因此在第二个while循环中,已经到末尾一下子就跳出了,page输出为"",解决方法是在注释出再次connect Http服务器,我希望只connect 一次就行。HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
                  String page = "";
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {//把html全部读到page中
page += new String(buffer);
}
String charset = getCharset(page);//解析html,获得字符编码
                  
                  //connection = (HttpURLConnection) url.openConnection();
//connection.connect();
BufferedInputStream in2 = new BufferedInputStream(connection.getInputStream());//再次从           page = "";
byte[] buffer2 = new byte[1024];
while (in2.read(buffer2) != -1) {//一下子跳出while
page += new String(buffer2, charset);
}

解决方案 »

  1.   

    你就用第一个BufferedInputStream 有问题吗?
      

  2.   

    ();
    reset();
      

  3.   

    把整个XML存放到一个临时区,等你知道编码后,再读那个XML,这不行么?
      

  4.   

    如果在第二个BufferedInputStream in2使用第一个in读,也一样,一下子就到结尾了
      

  5.   

    HttpUrlConnetion是url通信 既然是通信就是双方的 可以事先设置编码格式 
    你这样的写法in2永远得不到流 流都被第一个while读了 服务器在输出流后都会flush()操作的
      

  6.   

    一次貌似不行吧? 我觉得你可以将第一次读出的内容放入文件中,第二次采用拟想要的编码去读文件。再说你要HTML编码干嘛~ html的编码你完全可以通过解析HTML得到啊 不知道这个回答可以不
      

  7.   

    输入流可以做标记,方法,第二次读的时候reset方法复位就可以
      

  8.   

    和reset能行吗?
      学习了, 同事也曾遇到过类似的问题!
      

  9.   

    解决了,和reset,贴上代码HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            String page = "";
            BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
    in.(connection.getContentLength() + 1);//标志
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {//把html全部读到page中
                page += new String(buffer);
            }
            String charset = getCharset(page);//解析html,获得字符编码
    in.reset();//重置输入流       
            if (!in.Supported()) {
    (HttpURLConnection) url.openConnection();
     connection.connect();
    in = new BufferedInputStream(connection.getInputStream());
    }
    page = "";
    while (in.read(buffer) != -1) {
    page += new String(buffer, charset);
    }