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

时间:2016-02-17 22:01:05

标签: scala akka-http

我正在使用Akka Http 2.4.1向twitter api发布https请求。

根据他们的documentation,我需要两个httpheaders。即,授权和ContentType。

引用他们的文档:

请求必须包含一个Content-Type标头,其值为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将Content-Type标头包含在值application/x-www-form-urlencoded;charset=UTF-8中?

1 个答案:

答案 0 :(得分:19)

我认为,如果您将entity上的HttpRequest值更改为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