Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

spray

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...

like image 592
Andrey Avatar asked Sep 22 '13 21:09

Andrey


1 Answers

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
like image 65
4lex1v Avatar answered Nov 15 '22 05:11

4lex1v