Reputation: 915
I'm trying send a single API request to an URL in JSON but I'm able to send JSON request.
I tried following code in 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
How can I send above request as JSON?
Upvotes: 1
Views: 1424
Reputation: 123
You probably want to read https://doc.akka.io/docs/akka-http/current/common/json-support.html
Firstly you'll need a JSON library. The link above suggests spray-json. If you use that, then you can first marshal your Map to json string and then send the request as a string.
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)
Upvotes: 3