-1

I hava written a akka http client example,but i can not read HttpResponse body as a String,my code is below:

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)
    }
  }
 }
}

and the result is :

http://www.baidu.com

none value

who can tell me why? and how to write the code? thanks very much

leoluan
  • 33
  • 6

1 Answers1

0

Please ask in one spot at once, this question was answered on akka-user already, very quickly after it was asked.

Please the 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.

So you simply look into the Future before it had the chance to complete, so it's empty.

Instead use operations like map or onComplete to inspect it.

Konrad 'ktoso' Malawski
  • 13,102
  • 3
  • 47
  • 52