python - 如何在请求中添加 header

标签 python python-requests

是否有任何其他优雅的方式来向请求添加 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)

它接受两个参数 -

  1. 标题名称(之前定义的字典的键)
  2. Header value(前面定义的dict中对应key的值)

关于python - 如何在请求中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832536/

相关文章:

python - 如何加密django中的密码字段

python - 提交表单以从就业委员会抓取数据

Python 干+请求 : Not switching circut/changing IP address when using a session

python-3.x - Cloud Natural Language API 返回 socket.gaierror : nodename nor servname provided after performing Sentiment Analysis every now and then

python - 使用请求获取 .onion 域

python - PyPy + Storm ORM 不工作(cpyext 问题)

python - 如何更改包含数字的所有字符串单元格以在 pandas 中同时 float ?

python - 在python中将字典转换为数据框

python - a 和 b 的任意值使得 (a in b and b in a)==True

Python 请求多部分 HTTP POST