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