Akka HTTP如何使用Content-Type application / x-www-form-urlencoded发布singleRequest

时间:2017-04-04 12:52:20

标签: scala akka akka-http

我坚持使用Akka HTTP singleRequest()发送请求。我正在尝试处理Stripe API,它需要传入请求的application/x-www-form-urlencoded内容类型。

我尝试使用以下HTTP请求结构:

val authorization = Authorization(OAuth2BearerToken("some_token"))

Http().singleRequest(HttpRequest(
        uri = Uri("https://api.stripe.com/v1/customers"),
        method = HttpMethods.POST,
        headers = List(authorization),
        entity = FormData(Map("email" -> HttpEntity("test_1@email.com"))).toEntity(),
        protocol = HttpProtocols.`HTTP/1.1`)
      )

但是在Stripe日志中,我在Parsed Request POST Body部分中看到了以下内容:

(多部分形式:162)

所以问题是如何将内容类型设置为application/x-www-form-urlencoded

1 个答案:

答案 0 :(得分:4)

问题与FormData类型有关。要执行application/x-www-form-urlencoded请求,您需要使用FromData包中的akka.http.scaladsl.model

所以这是工作示例:

Http().singleRequest(HttpRequest(
        uri = Uri("https://api.stripe.com/v1/customers"),
        method = HttpMethods.POST,
        headers = List(authorization),
        entity = akka.http.scaladsl.model.FormData(Map("email" -> "user@email.com")).toEntity(HttpCharsets.`UTF-8`),
        protocol = HttpProtocols.`HTTP/1.1`)
      )