【问题标题】:How to consume a simple Restful service with Scala and Akka-Http 10.0.5如何使用 Scala 和 Akka-Http 10.0.5 使用简单的 Restful 服务
【发布时间】:2017-03-30 15:30:03
【问题描述】:

我花了一整天的时间想办法

  1. 使用远程restful json服务
  2. 将有效负载解组(反序列化)为案例类模型

google plus Akka 邮件列表中的人非常乐于助人,所以我认为如果有一个关于 SO 的工作示例也很好,以供将来参考。

【问题讨论】:

    标签: json scala rest unmarshalling akka-http


    【解决方案1】:

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

    【讨论】:

    • 要添加哪些依赖项?你有相同的 github 项目吗?
    • 刚看到我们的帖子,你知道了吗?
    猜你喜欢
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多