美文网首页开发中的小问题解决
获取远程文件大小 getContentLength()为-1之谜

获取远程文件大小 getContentLength()为-1之谜

作者: eagle隼 | 来源:发表于2018-11-08 20:08 被阅读0次

    获取远程文件大小 网上给的方案大部分是下面这条,但是会出现getContentLength()为-1的情况,搜索结果大部分为
    conn.setRequestProperty("Accept-Encoding", "identity");
    这条建议,但无效果

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setRequestProperty("Accept-Encoding", "identity");
            long contentLength = conn.getContentLength();
            conn.disconnect();
            return contentLength;
    

    看一下源码恍然大悟
    看一下下面两段代码就知道了

        public int getContentLength() {
            long l = getContentLengthLong();
            if (l > Integer.MAX_VALUE)
                return -1;
            return (int) l;
        }
        
        
        public long getContentLengthLong() {
            return getHeaderFieldLong("content-length", -1);
        }
    

    返回Long就可以了

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setRequestProperty("Accept-Encoding", "identity");
            long contentLength = conn.getContentLengthLong();
            conn.disconnect();
            return contentLength;
    

    相关文章

      网友评论

        本文标题:获取远程文件大小 getContentLength()为-1之谜

        本文链接:https://www.haomeiwen.com/subject/rzhgxqtx.html