Question

I need to programmatically log into a backend server, which returns an auth token as a cookie, then use that cookie to make requests going forward. I'm working in Lift 2.4, and everything I read seems to recommend using http-dispatch, but that has been cumbersome to learn! :-/ I'm working in dispatch-classic because of my SBT version (0.1-SNAPSHOT) and scala version 2.9.1. So I'm currently loading the dispatch 0.8.6 libraries.

I found the following at https://groups.google.com/forum/#!msg/dispatch-scala/m7oWv2YAtjQ/imnkYoCDVUcJ

For retrieving cookies:

To read a cookie from a response, you have to call the Response#getCookies method. For example, you could do something like this:

val res = Http(url("http://www.google.com/ig/api").addQueryParameter("weather", "Bonn, Germany"))
val response = for { r <- res } yield (r.getCookies, r.getResponseBody)

for adding cookies to subsequent requests:

url("http://www.google.com/ig/api").addCookie(cookie)

But I can't get this to work. My preference is code that works with dispatch 0.8.6, but if you can make it work in another version and don't see what that version won't work with my SBT and scala/Lift versions, I'll try using your recommended library version.

Was it helpful?

Solution

To get a the cookie, you should be able to do something like this:

Http(url("http://www.google.com/ig/api") <<? List("weather" -> "Bonn, Germany") >:> ((h) => h.get("Set-Cookie")))

That will request the URL, append the weather param, and then pass the response headers to a handler function which looks for the Set-Cookie header and returns an Option with the value, or None if it was not present.

To set a cookie, you can do:

Http(url("http://www.google.com/ig/api") <<? List("weather" -> "Bonn, Germany") <:< Map("Set-Cookie" -> "something") >| )

This will add the headers in the Map following the <:< directive, which in the case above includes the cookie. The >| handler simply ignores the response, but you can use any handler you want.

This guide is a pretty good reference for the different functions and handlers available.

I checked this out with 0.8.8, as I don't have the earlier version, and everything seemed to work for me. I can't sure for sure, but I think it should be the same with 0.8.6.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top