【问题标题】:How to get content-length for gZip enable file with HttpURLConnection?如何使用 HttpURLConnection 获取 gZip 启用文件的内容长度?
【发布时间】:2026-02-09 03:15:02
【问题描述】:

一些标头参数应该有助于检测正确的内容长度。

【问题讨论】:

    标签: android gzip


    【解决方案1】:
    /* Get download file size returned from http server header. */
    public static long getDownloadUrlFileSize(String downloadUrl) {
        long ret = 0;
        HttpURLConnection con = null;
        try {
            if (downloadUrl != null && !TextUtils.isEmpty(downloadUrl)) {
                URL url = new URL(downloadUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setRequestProperty("Accept-Encoding", "identity;q=1, *;q=0");
                System.out.println("Length : " + con.getContentLength());
                ret = con.getContentLength();
            }
        } catch (Exception ex) {
            Log.e(TAG_DOWNLOAD_MANAGER, ex.getMessage(), ex);
        } finally {
            if (con != null)
                con.disconnect();
            return ret;
    
        }
    }
    

    【讨论】:

    • 这是您问题的答案吗?