How to extract SSO cookie when using scalaj http library

135 views Asked by At

I have a HTTP response. I am trying to get the value for one of the header from it using scala. My code looks similar to below:

import scalaj.http.Http

val result = Http("http:///sample.com")
  .postData("""{"Username":"user1","password":"pass"""")
  .header("Content-Type", "application")
  .header("Accept", "text/plain")
val headers = result.headers.mkString

println("Headers: " + headers)

The headers look similar to below:

Cache-Control -> Vector(no-Store)
Content-Type -> Vector(text/html;charset=ISO-8859-l)
Set-Cookie -> Vector(SESSIONID=D122334;path=/a/b/c;SSO=000112233445)

Out of this header, I want to extract SSO value alone. Using below code, I am able to print them properly.

for((k,v) <- result.headers) println(s"key: $k\nvalue: $v\n")

Getting following result:

key: Cache-Control
value: Vector(no-Store)

key: Content-Type
value: Vector(text/html;charset=ISO-8859-l)

key: Set-Cookie
value: Vector(SESSIONID=D122334;path=/a/b/c;SSO=000112233445)

I want to extract the data for SSO under key Set-Cookie alone. I am aware of how to achieve this using python

I am pretty new to Scala. Can some one please help me out here?

1

There are 1 answers

4
Ivan Stanislavciuc On BEST ANSWER

Use cookies methods and filter cookie by name

  val ssoToken = Http("http:///sample.com")
    .postData("""???""")
    .header("Content-Type", "application")
    .header("Accept", "text/plain")
    .asBytes
    .cookies
    .find(_.getName == "SSO")
    .map(_.getValue)

You will get Some("tokenValue") when token is found, if you want to get it as String, you can do the following

ssoToken.getOrElse(sys.error("SSO Token not found"))

It will throw an exception if token is not found