将标头添加到python请求模块

dis*_*cky 83 python http-headers python-requests

之前我使用httplib模块在请求中添加标头.现在我正在尝试与requests模块相同的事情.

这是我正在使用的python请求模块:http: //pypi.python.org/pypi/requests

如何添加标题,request.postrequest.get说我必须foobar在标题中的每个请求中添加密钥.

tko*_*one 151

来自http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)
Run Code Online (Sandbox Code Playgroud)

您只需要使用标题创建一个dict(键:值对,其中键是标题的名称,值是该对的值),并将该dict传递给.get.post方法上的headers参数.

更具体的问题是:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
Run Code Online (Sandbox Code Playgroud)

  • 查看您发送和/或收到的回复可能会有所帮助。根据 [Requests Advanced Usage docs](http://docs.python-requests.org/en/master/user/advanced/#request-and-response-objects),使用 `r.headers` 访问标头服务器发送回和 `r.request.headers` 以查看您发送到服务器的标头。 (3认同)

nom*_*mer 32

您还可以这样设置Session对象的所有未来获取的标头,其中x-test将在所有s.get()调用中:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
Run Code Online (Sandbox Code Playgroud)

来自:http://docs.python-requests.org/en/latest/user/advanced/#session-objects

  • 上面的链接已经死了。https://requests.readthedocs.io/en/latest/user/advanced/#session-objects 有效。(我只是编辑帖子,但编辑队列已满) (2认同)