gpt4 book ai didi

python - urllib2 多个 Set-Cookie header 作为响应

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:03 24 4
gpt4 key购买 nike

我正在使用 urllib2 与发回多个 Set-Cookie header 的网站进行交互。然而,响应 header 字典只包含一个 - 似乎重复的键正在相互覆盖。

有没有办法用 urllib2 访问重复的 header ?

最佳答案

根据 urllib2 docs ,结果 URL 对象的 .headers 属性是一个 httplib.HTTPMessage(似乎没有记录,至少在 Python 文档中是这样)。

但是,

help(httplib.HTTPMessage)
...

If multiple header fields with the same name occur, they are combined
according to the rules in RFC 2616 sec 4.2:

Appending each subsequent field-value to the first, each separated
by a comma. The order in which header fields with the same field-name
are received is significant to the interpretation of the combined
field value.

因此,如果您访问 u.headers['Set-Cookie'],您应该得到一个 Set-Cookie header ,其值以逗号分隔。

确实如此。

import httplib
from StringIO import StringIO

msg = \
"""Set-Cookie: Foo
Set-Cookie: Bar
Set-Cookie: Baz

This is the message"""

msg = StringIO(msg)

msg = httplib.HTTPMessage(msg)

assert msg['Set-Cookie'] == 'Foo, Bar, Baz'

关于python - urllib2 多个 Set-Cookie header 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2454494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com