如何使用Scala和Akka-Http 10.0.5使用简单的Restful服务

时间:2017-03-30 15:30:04

标签: json scala rest unmarshalling akka-http

我花了一整天时间搞清楚如何

  1. 使用远程restful json服务
  2. 将有效负载解组(反序列化)为案例类模型
  3. google plus Akka邮件列表中的人非常有帮助,所以我认为在SO上有一个工作示例也很好,以备将来参考。

1 个答案:

答案 0 :(得分:2)

Akka-Http 10.0.5

package xxx

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.{ActorMaterializer, Materializer}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{BeforeAndAfter, FlatSpec, MustMatchers}
import org.scalatest.mock.MockitoSugar
import spray.json.DefaultJsonProtocol
import scala.concurrent.{Await, ExecutionContextExecutor, Future}
import akka.http.scaladsl.server.Directives

case class ColorBlob(url: String, averageColor: String, classificationColor: String)
case class ColorBlobsResponse(colorBlobs: Map[String, Option[ColorBlob]])

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
   implicit val format1 = jsonFormat3(ColorBlob)
   implicit val format2 = jsonFormat1(ColorBlobsResponse)
}

class ColorBlobRestTest
   extends FlatSpec
   with MockitoSugar
   with BeforeAndAfter
   with MustMatchers
   with ScalaFutures
   with JsonSupport
   with Directives {

   implicit val system: ActorSystem = ActorSystem()
   implicit val executor: ExecutionContextExecutor = system.dispatcher
   implicit val materializer: Materializer = ActorMaterializer()

   "this" should "work" in {
       val request = HttpRequest(method = HttpMethods.GET, uri = s"https://colorservice/colorblobs/en?productCodes=904655")
       val futureResponse: Future[HttpResponse] = Http().singleRequest(request)

       val futureColorBlobResponse: Future[ColorBlobsResponse] = futureResponse.flatMap { response: HttpResponse =>
           val entity: ResponseEntity = response.entity
           Unmarshal(entity).to[ColorBlobsResponse]
       }

       import scala.concurrent.duration._
       val colorBlobsResponse: ColorBlobsResponse = Await.result(futureColorBlobResponse, 1000.millis)

       assert(1==1)

    }
}