python中requests加请求头
时间: 2024-10-15 16:08:03 浏览: 38
在Python中,`requests`库是一个流行的HTTP客户端,它允许我们方便地发送各种HTTP请求,包括GET、POST等。如果你需要添加自定义请求头(如身份认证、用户代理、授权信息等),你可以这样做:
```python
import requests
# 定义请求头字典
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Authorization': 'Bearer your_access_token', # 如果有API token,替换为实际值
'Content-Type': 'application/json' # 请求体格式
}
# 发送GET请求,并指定请求头
response = requests.get('https://api.example.com/data', headers=headers)
print(response.status_code)
print(response.text)
# 如果你想发送POST请求,可以这样做:
post_data = {
'key': 'value'
}
response_post = requests.post('https://api.example.com/post', json=post_data, headers=headers)
```
这里,`headers`字典包含了你想要添加到请求中的所有头信息。当你调用`requests.get`或`requests.post`时,将这个字典作为`headers`参数传递即可。
阅读全文