如何将 HttpResponse 下载到文件中?

2024-03-31

我的 Android 应用程序使用发送多部分 HTTP 请求的 API。我成功地得到了这样的响应:

post.setEntity(multipartEntity.build());
HttpResponse response = client.execute(post);

响应是电子书文件(通常是 epub 或 mobi)的内容。我想将其写入具有指定路径的文件,让我们说“/sdcard/test.epub”。

文件可能高达 20MB,因此需要使用某种流,但我就是无法理解它。谢谢!


嗯,这是一个简单的任务,你需要WRITE_EXTERNAL_STORAGE使用权限..然后只需检索InputStream

InputStream is = response.getEntity().getContent();

创建文件输出流

FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "test.epub"))

从 is 读取并用 fos 写入

int read = 0;
byte[] buffer = new byte[32768];
while( (read = is.read(buffer)) > 0) {
  fos.write(buffer, 0, read);
}

fos.close();
is.close();

编辑,检查 tyoo

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 HttpResponse 下载到文件中? 的相关文章

随机推荐