3

I have an existing Akka HTTP HttpRequest and I want to add two headers to it.

val req: HttpRequest = ???
val hs: Seq[HttpHeader] = Seq(RawHeader("a", "b"))
req.addHeaders(hs)

Expected:

  • a new HttpRequest object with the additional headers

Actual:

  • .addHeaders expects a java.lang.Iterable and does not compile.

What is the recommended way of doing this in Scala?

There is a workaround, but it's a bit cludgy:

req.withHeaders(req.headers ++ hs)

Running Scala 2.12.8 and Akka HTTP 10.1.7.

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
akauppi
  • 17,018
  • 15
  • 95
  • 120

3 Answers3

4

Another workaround that is maybe a tiny sliver less cludgy. This is approximately how addHeaders is defined in the source. I unfortunately have no clue why addHeaders is not exposed in the scala api.

req.mapHeaders(_ ++ hs)
DrPhil
  • 377
  • 1
  • 12
  • Neat and thanks for the link to the sources - I check them too rarely. The real answer seems to be to implement .addHeaders on the Scala API but I don't really work with Akka HTTP at the moment, so won't be the one doing it. – akauppi Oct 30 '19 at 06:17
2

One alternative is to use foldLeft and addHeader:

val req: HttpRequest = ???
val hs: Seq[HttpHeader] = Seq(RawHeader("a", "b"))

hs.foldLeft(req)((r, h) => r.addHeader(h))
Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
  • 2
    It's still not very readable. I wonder if there's a reason why '.addheaders' is for Java API but not Scala. – akauppi Mar 18 '19 at 14:09
1

You can copy the existing HttpRequest to a new HttpRequest with headers

val req: HttpRequest = ???
val hs: Seq[HttpHeader] = Seq(RawHeader("a", "b"))
val reqWithHeaders: HttpRequest = req.copy(headers=hs)
  • Does this append to or replace the earlier headers? – akauppi Mar 20 '19 at 23:41
  • This replaces earlier headers. If you want earlier headers too change it to `val reqWithHeaders: HttpRequest = req.copy(headers = this.headers ++ hs)` – Shantiswarup Tunga Mar 21 '19 at 04:24
  • ..which is not very different from the workaround in my question. Anyhow, none of the answers have mentioned why Akka HTTP would support one syntax (`.addHeaders`) only for the Java API. That was intended to be the question. – akauppi Mar 21 '19 at 20:12
  • I am not sure but I think Scala HttpHeader extends jm.HttpHeader(akka.http.javadsl.model, Java Model) And `addHeaders, withHeaders` are methods of jm.HttpHeaders, So to override them method signature must be same as Jm.HttpHeaders method. Hence Scala `HttpHeaders` take java Iterable for some of its method. Again the answer is my understanding from the source code. Feel free to correct me. – Shantiswarup Tunga Mar 22 '19 at 06:28