我要使用apache HttpClient从HTTP服务器获取内容。我的HttpClient对象使用BrowserCompatSpec
类来处理cookie。
一些时间服务器返回HTTP响应头像这样:
"Set-Cookie: foo=deleted; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=-1404230328; path=/; domain=.domain.com"
在处理HttpClient中的响应期间,我收到警告:
Jul 01, 2014 8:15:12 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
WARNING: Invalid cookie header: "Set-Cookie: foo=deleted; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=-1404230328; path=/; domain=.domain.com".
Negative max-age attribute: -1404230328
因此,foo
Cookie未被删除且具有旧值。
RFC2109中的Max-Age属性描述:
Max-Age=delta-seconds
Optional. The Max-Age attribute defines the lifetime of the
cookie, in seconds. The delta-seconds value is a decimal non-
negative integer. After delta-seconds seconds elapse, the client
should discard the cookie. A value of zero means the cookie
should be discarded immediately.
我认为 - BrowserCompatSpec
正常工作,这个问题是服务器的缺陷。但我无法影响服务器行为。
如何忽略此警告并将foo
Cookie设置为已过期而不干预HttpClient lib?
答案 0 :(得分:2)
我在documentation (3.4. Custom cookie policy)找到了解决方案。使用本手册,我编写mySpecProvider
,使用重写的max-age属性处理程序创建新的cookie规范。
val mySpecProvider = new CookieSpecProvider {
override def create(context: HttpContext): CookieSpec = {
val spec = new BrowserCompatSpec()
spec.registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new MyCookieMaxAgeHandler())
spec
}
}
然后我创建了新的寄存器:
val cookiesRegistry = RegistryBuilder.create[CookieSpecProvider]()
.register("myspec", mySpecProvider)
.build()
并在客户端构建器中添加了注册
val clientBuilder = HttpAsyncClients.custom()
.setDefaultCookieSpecRegistry(cookiesRegistry)
使用新cookie规范的配置
val reqConfig = RequestConfig.custom()
.setCookieSpec("myspec")
MyCookieMaxAgeHandler
看起来像:
class MyCookieMaxAgeHandler extends BasicMaxAgeHandler {
override def parse(cookie: SetCookie, value: String) {
try {
if (value.toInt >= 0)
super.parse(cookie, value)
} catch {
case e: Exception =>
throw new MalformedCookieException("Invalid max-age attribute: " + value)
}
}
}
在所有这些操作之后,忽略了负的max-age属性。