将标头添加到python请求模块


Answers:


188

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)

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

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

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

2
查看您发送和/或接收的回复可能会有所帮助。根据Requests Advanced Usage文档,使用r.headers来访问服务器发回r.request.headers的标头以及查看要发送到服务器的标头。
哈珀维尔

44

您还可以执行此操作以为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'})

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.