是否有任何其他优雅的方式来向请求添加 header :
import requests
requests.get(url,headers={'Authorization', 'GoogleLogin auth=%s' % authorization_token})
不起作用,而 urllib2 起作用了:
import urllib2
request = urllib2.Request('http://maps.google.com/maps/feeds/maps/default/full')
request.add_header('Authorization', 'GoogleLogin auth=%s' % authorization_token)
urllib2.urlopen(request).read()
最佳答案
您可以通过将字典作为参数传递来添加 header 。
这应该有效:
requests.get(url,headers={'Authorization': 'GoogleLogin auth=%s' % authorization_token})
为什么您的代码不起作用?
您没有将字典传递给 headers 参数。您根据 add_header()
函数中定义的格式传递值。
根据文档,
requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)
headers – (optional) Dictionary of HTTP Headers to send with the Request.
为什么 request.add_header() 有效?
您使用 request.add_header()
添加 header 的方法之所以有效,是因为该函数在 urllib2
模块中定义。
Request.add_header(key, val)
它接受两个参数 -
- 标题名称(之前定义的字典的键)
- Header value(前面定义的dict中对应key的值)
关于python - 如何在请求中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832536/