如何使用 Akka-Streams HTTP 将整个 HttpResponse 主体读取为字符串

How to read whole HttpResponse body as a String with Akka-Streams HTTP

我已经写了一个 akka http 客户端示例,但是我无法将 HttpResponse 正文读取为字符串,我的代码如下:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpResponse, HttpRequest}
import akka.stream.ActorMaterializer
import scala.concurrent.duration._

import scala.util.{Failure, Success}


object TestHttp {
  def main(args: Array[String]) {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val url = "http://www.baidu.com"
    println(url)
    val responseFuture = Http().singleRequest(HttpRequest(uri = url))
    responseFuture.andThen {
      case Success(resp: HttpResponse) => {
        //println(resp.status.intValue())
        //println(resp.status.defaultMessage())
        //val aaaa = resp.entity.dataBytes.runFold(ByteString(""))(_ ++ _)
        //println(aaaa.value.get.get.decodeString("UTF-8"))
        //println(resp.entity.dataBytes.via(Framing.delimiter(ByteString("\n"),maximumFrameLength = 256,allowTruncation = true)).map(_.utf8String))
      val entity = resp.entity.toStrict(5 seconds).map(_.data.decodeString("UTF-8"))
      println(entity.value.getOrElse("none value"))
      //nodeCount=JsonUtil.nodeCount(entity.value.get.get)
    }
    case Failure(ex:Exception) => {
      println("http request error:"+ex.getMessage)
    }
  }
 }
}

结果是:

http://www.baidu.com

none值

谁能告诉我为什么?以及如何编写代码? 非常感谢

请一次性在一个地方提问,这个问题已经answered on akka-user了,很快就被问到了

ScalaDoc of value on Future:

If the future is not completed the returned value will be None. If the future is completed the value will be Some(Success(t)) if it contains a valid result, or Some(Failure(error)) if it contains an exception.

所以你只是在 Future 有机会完成之前查看它,所以它是空的。

而是使用 maponComplete 之类的操作来检查它。