How to convert from response 'set-cookie' header to request 'cookie' header in spray?
Asked Answered
Z

1

6

I'm attempting to use spray-client and spray-httpx and I'm having trouble figuring out how to convert 'set-cookie' headers from HttpResponse to a 'cookie' header that I'd like to set on an HttpRequest

val responseSetCookieHeaders = response.headers filter { _.name == "Set-Cookie" }
...
val requestCookieHeader:HttpHeader = ???
...
addHeader(requestCookieHeader) ~> sendReceive ~> { response => ??? }

I do see spray.http.HttpHeaders.Cookie, but I see no way to convert from an instance of HttpHeader to HttpCookie...

Zymotic answered 22/9, 2013 at 21:20 Comment(0)
M
9

HttpHeaders.Cookie is a case class with an unapply method. So you can extract it from response with a simple function:

def getCookie(name: String): HttpHeader => Option[HttpCookie] = {
  case Cookie(cookies) => cookies.find(_.name == name)
}

That's a bit more general case, but i think the solution is clear.

I would do this in the following way:

// some example response with cookie
val httpResponse = HttpResponse(headers = List(`Set-Cookie`(HttpCookie("a", "b"))))

// extracting HttpCookie
val httpCookie: List[HttpCookie] = httpResponse.headers.collect { case `Set-Cookie`(hc) => hc }

// adding to client pipeline
val pipeline = addHeader(Cookie(httpCookie)) ~> sendReceive
Mamiemamma answered 22/9, 2013 at 22:3 Comment(3)
from what i can see the matching should be done on Set-Cookie: val responseSetCookieHeader:HttpHeader = ???; responseSetCookieHeader match { case HttpHeader.Set-Cookie(c) => println(c.content) }. thank you for putting me on the right track!Zymotic
basically, i ended-up doing: responseSetCookieHeaders map { case HttpHeaders.Set-Cookie(c) => s"${c.name}=${c.content}" } mkString "; " if you update your answer with matching on "Set-Cookie" instead of "Cookie" I'll accept itZymotic
just add one last line showing how to convert from List[HttpCookie] to HttpHeader: HttpHeaders.Cookie(httpCookie)Zymotic

© 2022 - 2024 — McMap. All rights reserved.