此前在Android 11正常运行的文件下载创建功能突然失效是什么原因?
故障根因与修复方案
1 核心故障原因
- GET请求配置错误:你在代码中给GET请求加了
urlConnection.setDoOutput(true)配置,该配置仅用于需要向服务器提交请求体的POST/PUT类请求,GET请求添加后会修改请求属性,属于不符合HTTP规范的请求。你此前功能正常是因为服务器之前对这类错误请求做了兼容,近期服务器调整了校验规则,直接断开了携带错误属性的请求连接,就触发了你遇到的unexpected end of stream异常。 - 你最初怀疑的存储权限问题和本次故障无关,不管是
getExternalFilesDir(null)还是getFilesDir()都是应用专属目录,不需要额外存储权限,文件创建失败是因为请求提前断开,下载逻辑没有执行到写文件的环节。
修复第一步:直接删除urlConnection.setDoOutput(true);这行代码。
2 配套优化点(避免隐性异常)
- 补充资源关闭逻辑:你原有代码只关闭了输出流,输入流未显式关闭,异常场景下会出现资源泄漏,建议把所有流操作放到finally块统一关闭。
- 增加缓冲区刷出、目录校验逻辑:写文件完成后加flush操作保证缓冲区内容全部写入磁盘,文件创建前校验父目录存在,避免极端场景下的写文件失败。
- 存储配置可以按需回退:你原有
getExternalFilesDir(null) + requestLegacyExternalStorage="true"的配置在Android 11上完全合规,如果你的文件需要允许用户通过其他应用查看,getExternalFilesDir()是比getFilesDir()更合理的选择,修复下载代码后可以按需回退存储配置。
3 修复后完整代码示例
public class DownloadFile implements Runnable { private String mUrlString; private String mFileName; private CountDownLatch mLatch; public DownloadFile(String urlString, String fileName, CountDownLatch latch) { mUrlString = urlString; mFileName = fileName; mLatch = latch; } public void run() { HttpURLConnection urlConnection = null; FileOutputStream fileOutput = null; InputStream inputStream = null; Spine.mDownloadStatus = false; try { URL url = new URL(mUrlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setUseCaches(false); urlConnection.connect(); File file = new File(Spine.dataDir, mFileName); // 校验父目录存在 file.getParentFile().mkdirs(); fileOutput = new FileOutputStream(file); inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } // 强制刷出缓冲区内容到磁盘 fileOutput.flush(); Spine.mDownloadStatus = true; } catch (IOException e) { Spine.mErrorString = e.getMessage(); } finally { // 异常场景下也能正常关闭所有资源 try { if (inputStream != null) inputStream.close(); } catch (IOException ignore) {} try { if (fileOutput != null) fileOutput.close(); } catch (IOException ignore) {} if (urlConnection != null) urlConnection.disconnect(); } mLatch.countDown(); } }
内容的提问来源于stack exchange,提问作者Jeff G
相关产品推荐
相关产品推荐

