1

JSONを返す残りのサービスへのGET HTTP呼び出しを行います。json を scala オブジェクトに解析したいのですが、ここで行き詰まりました。Akka API を使用していますが、Akka のResponseEntityからコンテンツを取得できません。

これが私の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 を取得するのは簡単です。2 つの方法がありますが、json で再生 (つまり、play を使用して解析) できるように、コンテンツ自体を取得するにはどうすればよいですか?

4

1 に答える 1

0

Binary コンテンツ タイプには entity.data.toString を使用するか、次のコードを使用できます。

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-06-16T04:53:50.433 に答える