如何在 akka http 中传递 Json 内容类型

How to pass Json content type in akka http

我正在尝试向 JSON 中的 URL 发送单个 API 请求,但我能够发送 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 的形式发送上述请求?

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

首先您需要一个 JSON 库。上面的 link 表示 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)