getContentLength return -1 当我尝试下载 zip 文件时

getContentLength return -1 when i try to download zip file

我尝试从服务器下载 zip 文件并显示进度条,但我得到 conexion.getContentLength()=-1。这就是为什么我无法显示进度对话框,下载工作正常。我的代码如下:

  URLConnection conection = fileUrl.openConnection();
  conection.connect();
  int lenghtOfFile = conection.getContentLength();

but I get -1

当未设置响应的 Content-Length header 字段时,这是预期的行为。这是 backend-side 问题,而不是客户端问题。作为解决方法,您可以显示不确定的 ProgressBar(旋转的)而不是确定的

尝试 HttpURLConnection 而不是 URLConnection 并设置 setChunkedStreamingMode(100);

HttpURLConnection urlConnection = (HttpURLConnection) fileUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(100);
urlConnection.connect();
int lenghtOfFile = urlConnection.getContentLength();