HttpURLConnection.getContentLength()返回-1:网络图片下载问题求助
解决HttpURLConnection.getContentLength()返回-1的问题
我来帮你捋捋这个问题哈!你遇到的getContentLength()返回-1的情况,大概率是这两个原因导致的:
- 服务器未返回Content-Length响应头:很多服务器现在会用分块传输编码(
Transfer-Encoding: chunked)发送数据,这种情况下服务器不会提前告知总内容长度,getContentLength()自然就返回-1了。 - 请求设置冗余:你代码里的
httpConnection.setDoOutput(true)是多余的——GET请求是从服务器读取数据,不需要向服务器写入输出流,这个设置可能干扰服务器的响应逻辑,导致响应头异常。
对应的解决办法
1. 移除不必要的请求设置
先把setDoOutput(true)删掉,修改后的基础请求代码如下:
URL url = new URL(downloadPath); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("GET"); // 移除无意义的setDoOutput(true) httpConnection.connect();
2. 不依赖Content-Length,直接读取流
如果服务器确实用了分块传输,那就别纠结长度了,直接循环读取输入流直到结束就行,完整示例代码:
File file = new File(filePath); try (OutputStream outputStream = new FileOutputStream(file); InputStream inputStream = httpConnection.getInputStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); }
3. 改用getContentLengthLong()(可选)
如果你的文件可能超过int的最大值(2GB),可以用getContentLengthLong()替代getContentLength(),它返回long类型能避免溢出,但如果是分块传输的情况,它还是会返回-1,所以核心还是要处理无长度的流读取。
内容的提问来源于stack exchange,提问作者m.sajjad.s
相关产品推荐
相关产品推荐

