【问题标题】:Get content from Akka ResponseEntity in Scala从 Scala 中的 Akka ResponseEntity 获取内容
【发布时间】:2016-10-16 20:16:34
【问题描述】:

我对返回 json 的 rest 服务进行了 GET HTTP 调用。我想将 json 解析为 scala 对象,但在这里我被卡住了。我正在使用 Akka api,但无法从 Akka 的 ResponseEntity

中检索 content

这是我的 sbt 文件:

name := "ScalaHttp"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies ++={
  val akkaV = "2.4.5"
  Seq(
    "com.typesafe.akka"         %%  "akka-http-core"    % akkaV,
    "com.typesafe.play"         %%  "play-json"         % "2.4.0-M3"
  )
}

这是应用程序

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.stream.ActorMaterializer

import scala.concurrent.ExecutionContext.Implicits.global


object Sender {
  def main(args: Array[String]): Unit = {

    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()

    Http().singleRequest(HttpRequest(uri = "http://declinators.com/declinator?noun=komunikacja")) foreach {
      y => println(y.entity)
        println(y.entity.getContentType())
        println(y.entity.contentType)
    }
  }
}

打印出来:

HttpEntity.Strict(application/json,{"nominative":"komunikacja","genitive":"komunikacji","dative":"komunikacji","accusative":"komunikację","instrumental":"komunikacją","locative":"komunikacji","vocative":"komunikacjo"})
application/json
application/json

问题来了:
1. 为什么 ResponseEntity 提供 getContentType() 和 contentType()?他们返回同样的东西。 2.获取contentyType很简单,有两种方法,但是我怎样才能获取内容本身,所以我可以用json播放(即使用play解析它)!

【问题讨论】:

  • 您可以使用y.entity.data 访问实体数据,它返回ByteString。在您的情况下,只需在 ByteString 上调用 utf8String 即可获得可以解析的 json 字符串。
  • getContentType() getter 仅用于 Java 兼容性。在 Scala 中,您应该使用 contentType

标签: scala akka httpentity


【解决方案1】:

您可以将 entity.data.toString 用于 Binary 内容类型,或以下代码段

data.decodeString(nb.charset.value)

请按照此处的 HttpEntity.Strict.toString 实现了解详细信息:

https://github.com/akka/akka/blob/master/akka-http-core/src/main/scala/akka/http/scaladsl/model/HttpEntity.scala#L316

【讨论】:

    猜你喜欢
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    相关资源
    最近更新 更多