如何在Akka HTTP中传递Json内容类型

时间:2019-06-12 18:58:28

标签: scala akka-http

我正在尝试将单个API请求发送到JSON中的URL,但是我能够发送JSON请求。

我尝试在scala中遵循以下代码

val uri = "https://test.com/mock-sms/receive"

          val body = FormData(Map("to" -> "+837648732&", "content" -> "Hello")).toEntity
          val respEntity: Future[ByteString] = for {
            request <- Marshal(body).to[RequestEntity]
            response <- Http().singleRequest(HttpRequest(method = HttpMethods.POST, uri = uri, entity = request))
            entity <- Unmarshal(response.entity).to[ByteString]
          } yield entity

如何将上述请求作为JSON发送?

1 个答案:

答案 0 :(得分:1)

您可能想阅读https://doc.akka.io/docs/akka-http/current/common/json-support.html

首先,您需要一个JSON库。上面的链接建议Spray-json。如果使用了该方法,则可以先将Map编组为json字符串,然后以字符串形式发送请求。

    val uri = "https://test.com/mock-sms/receive"
    val body = Map("to" -> "+837648732&", "content" -> "Hello").toJson
    val entity = HttpEntity(ContentTypes.`application/json`, body.toString())
    val request = HttpRequest(method = HttpMethods.POST, uri = uri, entity = entity)
    val futureRes = for {
      resp <- Http().singleRequest(request)
      res <-  Unmarshal(resp.entity).to[String]
    } yield res
    val res = Await.result(future, 10.seconds)