繁体   English   中英

使用 Http4s 客户端设置 Cookie

[英]Setting Cookies using Http4s Client

我正在使用 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 客户端编写相同的代码。 然后一切正常。 下面的代码和上面的代码做的完全一样。

  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

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

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

如果您想附加发送到您的客户端的 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM