简体   繁体   中英

Akka http add header to POST request with body

I have an akka http route that accepts a json in the body of the request. I am trying to test that route by using akka http test kit.

val header = RawHeader("Content-Type", "application/json")
Post("/tasks", trigger.asJson.noSpaces) ~> addHeader(header) ~>
    addCredentials(OAuth2BearerToken(VALID_TOKEN)) ~> Route.seal(route) ~> check {
    status shouldBe StatusCodes.OK
  }

This test is failing with message

415 Unsupported Media Type was not equal to 200 OK 

How do i properly add the content type header to the request?

Let akka-http create RequestEntity on its own instead of passing json as String yourself.

You just need to pass trigger as the second parameter of Post.apply as is.

Post("/tasks", trigger) ~> addCredentials(OAuth2BearerToken(VALID_TOKEN)) ~> Route.seal(route) ~> check {
  status shouldBe StatusCodes.OK
}

This will require a ToEntityMarshaller[Trigger] available in your implicit context.

And you can add it in the same way as you do in you route definition by importing/extending de.heikoseeberger.akkahttpargonaut.ArgonautSupport and argonaut CodecJson[Trigger] if you use argonaut for example.

In case you want to pass arbitrary string value, do

Post("/tasks").withEntity(ContentTypes.`application/json`, someJsonAsString) ~> addCredentials(OAuth2BearerToken(VALID_TOKEN)) ~> Route.seal(route) ~> check {
   status shouldBe StatusCodes.OK
}

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