在 HTTP POST header 中包含 session

Include session in HTTP POST header

我需要使用 Python 将 JSON 上传到 API。我有一个 session header 添加到 POST 请求以授权请求。 session 格式如下:

session=值=

我一直在尝试将它作为 header 添加到 python urllib2 库中,但是 API 仍然给我一个 401 Unauthorized。到目前为止,我是这样做的:

req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
req.add_header('Set-Cookie', 'session=value=')
response = urllib2.urlopen(req, data=json.dump(data))

我一直在阅读 urllib2 文档以及 http cookie,但我找不到通过 headers 发送此 cookie 的明确方法。有人可以在这里说明如何做吗? 不幸的是,出于隐私问题,我无法显示 url 和 cookie。

提前致谢。

您应该使用 Cookie 而不是 Set-Cokkie。其他还好

req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
req.add_header('Cookie', 'session=value=')
response = urllib2.urlopen(req, data=json.dump(data))

当服务器响应时,它使用Set-Cookie在客户端持久化一个cookie,当客户端想要回调时,它只是使用Cookie作为头。