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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (29)

我正在尝试向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库。上面的链接表明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)

扫码关注云+社区

领取腾讯云代金券