首页 > HttpURLConnection 问题

HttpURLConnection 问题

为什么 String key = DigestUtils.md5Hex(conn.getInputStream()); 使用后,后面就不能用了,难道必须要两次 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 吗?

    @Test
    public void test() {
        try {
            URL url = new URL("http://www.baidu.com/img/270_fbe71c0815a61fd81c5b89573a002f38.png");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");// 声明请求方式
            conn.setConnectTimeout(6 * 1000);// 设置连接超时
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
            conn.setRequestProperty("Accept-Encoding", "identity");
            
            if (conn.getResponseCode() == 200) {
                String key = DigestUtils.md5Hex(conn.getInputStream());
                System.out.println(key);
                
                BufferedImage img = ImageIO.read(conn.getInputStream());
                int width = img.getWidth();
                int height = img.getHeight();
                System.out.println(width);
                System.out.println(height);
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

因为输入流用完一次后,当前位置就走到流的末尾了,当然读不到数据了。

建议你在第一次使用前,用mark()方法标记一下,在第二次使用前用reset方法重置到开始位置。

试试看行不行。


输入流在读取的时候,读取之后的数据就不会再次被读取(有些流可以通过设置Position的位置重复读取,这里不考虑),所以你需要将输入流中的内容读取到一个byte[]缓存起来,以重复使用

【热门文章】
【热门文章】