scala - scalaj-http - “执行”方法正在返回“流已关闭”
问题描述
我想使用 scalaj-http 库从 http 连接下载大小为 31gb 的字节内容文件。'asBytes' 不是一个选项,因为它返回一个字节数组。
我尝试使用返回输入流的“执行”方法,但是当我执行下面的程序时,它返回流已关闭。我不认为我正在阅读两次流。
我做错了什么?
val response: HttpResponse[InputStream] = Http(url).postForm(parameters).execute(inputStream => inputStream)
if (response.isError) println(s"Sorry, error found: ${response.code}")
else {
val is: InputStream = response.body
val buffer: Array[Byte] = Array.ofDim[Byte](1024)
val fos = new FileOutputStream("xxx")
var read: Int = 0
while (read >= 0) {
read = is.read(buffer)
if (read > 0) {
fos.write(buffer, 0, read)
}
}
fos.close()
}
解决方案
您无法导出,inputStream
因为流将在执行方法结束时关闭。您应该在执行中使用流,如下所示:
val response = Http(url).postForm(parameters).execute { is =>
val buffer: Array[Byte] = Array.ofDim[Byte](1024)
val fos = new FileOutputStream("xxx")
var read: Int = 0
while (read >= 0) {
read = is.read(buffer)
if (read > 0) {
fos.write(buffer, 0, read)
}
}
fos.close()
}
if (response.isError) println(s"Sorry, error found: ${response.code}")
推荐阅读
- html - Angular 6 测验表格:在页面之间绑定和保存数据
- javascript - 为什么循环遍历所有 div 的孩子 + 删除它们仅在 X 使用后才开始工作?
- android - 打开然后关闭 youtube 视频的 Android 应用程序
- php - Slim REST API 调用错误,没有错误消息(JQuery)
- three.js - 加载 GLTF 后 Aframe 加载光照贴图 - 光照贴图未显示
- python - 创建一个子类,其超类仅在创建时才知道
- angular - 多次单击提交按钮时,angular4 ngSubmit 会触发多次?
- swift - NSAccessibilityProtocol vs NSAccessibility(保持 XCode 9 & 10 兼容性)
- python - 如何在 numpy 中沿小维度优化点积?
- oracle - How to access and query objects passed as parameter to a procedure while converting from Oracle to postgresql