You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sttp+ZioBackend:将Byte类型ZStream转为按行String流

解决方案

要把Stream[Throwable, Byte]转换成按行分割的Stream[Throwable, String],可以直接利用ZIO Stream提供的文本处理操作来实现:

核心转换逻辑

针对字节流依次调用解码和拆分行的方法即可完成转换:

def byteStreamToLineStream(byteStream: Stream[Throwable, Byte]): Stream[Throwable, String] =
  byteStream.utf8Decode.splitLines
  • utf8Decode:将字节流解码为UTF-8格式的字符串流,解码遇到无效字节时会抛出对应异常
  • splitLines:自动兼容不同平台的换行符(\n、\r\n等),把连续的字符串流拆分成独立的行字符串

整合到HTTP请求代码中

把转换逻辑应用到响应体的处理上,完整代码示例:

import sttp.client3._
import zio._
import zio.stream._

val sttpBackend: SttpBackend[Task, ZioStreams] = ???

val request =
  basicRequest
    .post(uri"...")
    .response(asStreamUnsafe(ZioStreams))
    .readTimeout(Duration.Inf)

val lineStreamResponse: ZIO[Any, Throwable, Response[Either[String, Stream[Throwable, String]]]] =
  response.map { resp =>
    resp.mapBody {
      case Left(errorMsg) => Left(errorMsg)
      case Right(byteStream) => Right(byteStream.utf8Decode.splitLines)
    }
  }

如果需要处理非UTF-8编码的响应体,可以指定对应的字符集:

import java.nio.charset.StandardCharsets

byteStream.decode(StandardCharsets.GBK).splitLines

内容的提问来源于stack exchange,提问作者Izbassar Tolegen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:10:30