将标题添加到请求模块

问题描述:

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

Earlier I used httplib module to add a header in the request. Now I am trying the same thing with the requests module.

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

This is the python request module I am using: http://pypi.python.org/pypi/requests

如何将标头添加到request.post()request.get().假设我必须在标题的每个请求中添加foobar键.

How can I add a header to request.post() and request.get(). Say I have to add foobar key in each request in the header.

来自 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)

您只需要创建一个带有标题的字典(键:值对,其中键是标题的名称,值是该对的值),然后将该字典传递给标头上的headers参数.get.post方法.

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

因此更具体地针对您的问题:

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)