Reputation: 373
I'm trying to figure out how to create a basic HTTP POST request with the Akka HTTP library. This is what I came up with:
val formData = Await.result(Marshal(FormData(combinedParams)).to[RequestEntity], Duration.Inf)
val r = HttpRequest(POST, url, headers, formData)
The thing is that it seems a bit non-idiomatic to me. Are there other ways to create a HttpEntity from FormData? Especially the fact that I have to use Await
or return a Future even though the data is readily available seems overly complex for such a simple task.
Upvotes: 12
Views: 10399
Reputation: 126
You can also use RequestBuilding
:
Http().singleRequest(RequestBuilding.Post(url, formData)).flatMap(Unmarshal(_).to[String])
Upvotes: 0
Reputation: 373
Apparently a toEntity
method was added to the FormData class at some point. So this now seems like the simplest solution to the problem:
val formData = FormData(combinedParams).toEntity
val r = HttpRequest(POST, url, headers, formData)
Upvotes: 6
Reputation: 10428
You can use Marshal
in a for comprehension with other Futures, such as the ones you need to send the request and unmarshall the response:
val content = for {
request <- Marshal(formData).to[RequestEntity]
response <- Http().singleRequest(HttpRequest(method = HttpMethods.POST, uri = s"http://example.com/test", entity = request))
entity <- Unmarshal(response.entity).to[String]
} yield entity
Upvotes: 18