简体   繁体   中英

Idiomatic way to create a basic HTTP Post request with Akka HTTP

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.

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

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)

您还可以使用RequestBuilding

Http().singleRequest(RequestBuilding.Post(url, formData)).flatMap(Unmarshal(_).to[String])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM