8

I am using Akka Http 2.4.1 to post a https request to the twitter api.

According to their documentation, I need two httpheaders. Namely, Authorization and ContentType.

To quote their docs:

The request must include a Content-Type header with the value of application/x-www-form-urlencoded;charset=UTF-8.

Here is my code:

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`))

How can I include the Content-Type header with the value application/x-www-form-urlencoded;charset=UTF-8 using Akka-http 2.4.1?

Rob O'Doherty
  • 549
  • 3
  • 14
  • 1
    Content-Type will be set automatically based on the type of entity being included in the request. In your case you are setting your http entities content type to `text/plain(UTF-8)`. – cmbaxter Feb 17 '16 at 22:04
  • Thanks for the additional explanation. Helpful! – Rob O'Doherty Feb 18 '16 at 10:42

1 Answers1

22

I think if you change the entity value on your HttpRequest to FormData like so:

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`)
)

Then you should get the Content-Type to be automatically set for you to application/x-www-form-urlencoded;charset=UTF-8

cmbaxter
  • 35,283
  • 4
  • 86
  • 95