我正在使用Http4s库对REST web服务进行HTTP调用。rest 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发布于 2020-02-19 23:11:09
您的cookie似乎没有用于响应。您是否尝试过使用以下方法:
val cookie = org.http4s.ResponseCookie("token", su.token.getOrElse("No token"), httpOnly = true, secure = true)
Ok("resp").map(_.addCookie(cookie))发布于 2021-07-28 13:38:04
如果您想附加发送到客户端的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
https://stackoverflow.com/questions/39694931
复制相似问题