如何在 Akka-http 2.4.1 中包含 application/x-www-form-urlencoded HttpHeader?

How to include application/x-www-form-urlencoded HttpHeader in Akka-http 2.4.1?

我正在使用 Akka Http 2.4.1 post 向 Twitter api.

发送 https 请求

根据他们的 documentation,我需要两个 httpheader。即 Authorization 和 ContentType。

引用他们的文档:

请求必须包含一个 Content-Type header,值为 application/x-www-form-urlencoded;charset=UTF-8.

这是我的代码:

val authorization = Authorization(BasicHttpCredentials(key, secret))

/*
   This header is removed from the request with the following explanation!
   "Explicitly set HTTP header 'Content-Type: application/x-www-form-urlencoded;' is ignored, illegal RawHeader"
*/
val contentType = RawHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")

Http().singleRequest(
    HttpRequest(
        uri = Uri("https://api.twitter.com/oauth2/token"),
        method = HttpMethods.POST,
        headers = List(authorization, contentType),
        entity = HttpEntity(`text/plain(UTF-8)`, "grant_type=client_credentials"),
        protocol = HttpProtocols.`HTTP/1.1`))

如何使用 Akka-http 2.4.1 包含值 application/x-www-form-urlencoded;charset=UTF-8Content-Type header?

我认为如果您将 HttpRequest 上的 entity 值更改为 FormData,如下所示:

HttpRequest(
    uri = Uri("https://api.twitter.com/oauth2/token"),
    method = HttpMethods.POST,
    headers = List(authorization),
    entity = FormData("grant_type" -> "client_credentials").toEntity,
    protocol = HttpProtocols.`HTTP/1.1`)
)

那么你应该让 Content-Type 自动为你设置为 application/x-www-form-urlencoded;charset=UTF-8