微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 sttp

如何解决使用 sttp

我已经设置了一个 api,它在给定的路径中发送文件的数据。我正在尝试从 api 获取 .xlsx 文件并将其传递给 XSSFWorkbook 以进行进一步处理。为此,我尝试了两种方式:

  1. 内容传递给 InputStream,然后将其传递给 XSSFWorkbook。 这是一个错误 invalid code lengths set
    val excelData = getFileContent(remoteFsUrl,filePath,apiKey).right.get
    val excelFile = IoUtils.toInputStream(excelData,"UTF-8")
    val reader = new XSSFWorkbook(OPCPackage.open(excelFile)) <-- error here
    reader.getSheetAt(0)
  1. 文件保存在某个本地路径中并读取它。 但它破坏了 xlsx 文件,就好像我试图将响应保存为 Postman 中的文件一样。
    val excelData = getFileContent(remoteFsUrl,apiKey).right.get
    new PrintWriter("filename") { write(excelData); close }
    val excelFile = new FileInputStream(new File(filePath))
    val reader = new XSSFWorkbook(excelFile)
    reader.getSheetAt(0)

我可以知道上述方法是否有问题或有什么更好的方法吗?

P.S:我提到的 API 是建立在 fastapi 之上的。

编辑: getFileContent

的实现
def getFileContent(url: String,path: String,apiKey: String,timeOut: Int = 300) = {
        val request = basicRequest
            .get(uri"$url/fetchfile?file_path=$path&access_token=$apiKey")
        implicit val backend: SttpBackend[Identity,nothing,nothingT]
        = HttpURLConnectionBackend(options = SttpBackendOptions.connectionTimeout(timeOut.seconds))
        val response = request.readTimeout(timeOut.seconds).send()
        val someFile = new File("path/t.xlsx")
        val data = response.body.right.get.getBytes
        val bos = new bufferedoutputstream(new FileOutputStream(someFile))
        bos.write(data)
        bos.close()
        println(response)
        response.body
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。