2

我正在使用 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
4

2 回答 2

0

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

val cookie = org.http4s.ResponseCookie("token", su.token.getOrElse("No token"), httpOnly = true, secure = true)
Ok("resp").map(_.addCookie(cookie))
于 2020-02-19T15:11:09.387 回答
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

于 2021-07-28T05:38:04.170 回答