我尝试将单个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格式发送上述请求?
发布于 2019-06-13 03:44:03
您可能想要阅读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)
https://stackoverflow.com/questions/56568743
复制相似问题