代码之家  ›  专栏  ›  技术社区  ›  Isvara

如何封送未来的[源[…]]与akka http的HttpResponse?

  •  2
  • Isvara  · 技术社区  · 7 年前

    我有以下方法返回一个 Future[Source[List[String]]] (CSV文件的前两行):

    def get(url: String, charset: String, delimiter: Char, quote: Char, escape: Char) = {
        val scanner = CsvParsing.lineScanner(
            delimiter.toByte,
            quote.toByte,
            escape.toByte
        )
    
        val request = HttpRequest(GET, Uri(url)).withHeaders(`User-Agent`(UserAgent))
    
        Http(system)
            .singleRequest(request)
            .map { response =>
                response.entity.withoutSizeLimit.dataBytes
                    .viaMat(scanner)(Keep.left)
                    .map(row =>
                        row.map(bs =>
                            bs.decodeString(charset)
                        )
                    )
                    .take(2)
            }
    }
    

    返回的 Future 传递给 complete ,它使用以下命令将其封送到数组的JSON数组:

    implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()
    

    response 并返回不同的 HttpResponse 如果不是200。这样做的最好方法似乎是将 Future[Source[...]] HttpResponse 在该方法中,则其返回类型为 HttpResponse

    1 回复  |  直到 7 年前
        1
  •  0
  •   Isvara    7 年前

    好的,最后我用了一种不同的方法。

    Http(system).singleRequest(request)
        .flatMap { response =>
            response.status match {
                case StatusCodes.OK =>
                    val compression = CompressionChooser.choose(url, gzip, response)
                    response.entity.withoutSizeLimit.dataBytes
                        .via(compression.decoder.decoderFlow)
                        .viaMat(scanner)(Keep.left)
                        .map(_.map(_.decodeString(charset)))
                        .take(2)
                        .runWith(Sink.seq)
                        .map { rows =>
                            val json = Json.toJson(rows)
                            HttpResponse(
                                StatusCodes.OK,
                                entity = HttpEntity(ContentTypes.`application/json`, json.toString)
                            )
                        }
    
                case _ => Future successful HttpResponse(StatusCodes.BadRequest, entity = "Error")
            }
        }