使用Http4s客户端设置Cookie

时间:2016-09-26 04:53:36

标签: scala http4s

我正在使用Http4s库对REST Web服务进行HTTP调用。其余的Web服务要求我设置身份验证cookie。

我已编写以下代码来设置此Cookie。

val client = PooledHttp1Client()
val uri = Uri.uri("http://localhost/restService")
val req = Request(GET, uri)
req.headers.put(`Content-Type`(MediaType.`application/json`))
val cookie = org.http4s.Cookie("foo_session", getLoginSessionId, domain = Some("localhost"), path=Some("/"))
req.headers.put(org.http4s.headers.Cookie(cookie))    
val task = client.expect[Response](req)
val list = task.run
list.response.foreach(println)
client.shutdownNow()

当我运行此代码时,我收到401错误,这意味着Web服务无法识别cookie已设置。

现在如果我使用apache http client编写相同的代码。一切正常。下面的代码与上面的代码完全相同。

  val get = new HttpGet(s"http://localhost/restService")
  get.setHeader("Content-type", "application/json")
  val client = new DefaultHttpClient()
  val respHandler = new BasicResponseHandler
  val cookieStore = new BasicCookieStore()
  val cookie1 = new BasicClientCookie("foo_session", getLoginSessionId)
  cookie1.setDomain("localhost")
  cookie1.setPath("/")
  cookieStore.addCookie(cookie1)
  val localContext = new BasicHttpContext()
  localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore)
  localContext
  val responseString = client.execute(get, respHandler, cookieContext)
  val list = parse(responseString).extract[Response]
  list.response.foreach(println)
  list.response

2 个答案:

答案 0 :(得分:0)

您的Cookie似乎没有用于响应。 您是否尝试过使用以下方法:

val cookie = org.http4s.ResponseCookie("token", su.token.getOrElse("No token"), httpOnly = true, secure = true)
Ok("resp").map(_.addCookie(cookie))

答案 1 :(得分:0)

如果你想附上发送给你客户端的cookie服务器,你可以试试Cookie Jar。 https://github.com/http4s/http4s/blob/main/client/src/main/scala/org/http4s/client/middleware/CookieJar.scala

Http4s 会严格检查来自服务器的 cookie,因此某些 cookie 条目可能没有得到回复。如果是这样,你可以试试这个: https://github.com/chenharryhua/nanjin/blob/master/http/src/main/scala/com/github/chenharryhua/nanjin/http/client/middleware/CookieBox.scala