在Python中,使用`requests`库发送HTTP请求时,可以通过以下两种方式在请求头中携带参数:
设置请求头
使用`headers`参数传递请求头信息,这是一个字典,键是请求头名称,值是对应的值。例如:
import requestsurl = 'https://api.example.com/data'headers = {'User-Agent': 'My-Custom-User-Agent/1.0','Accept': 'application/json','Authorization': 'Bearer your_token_here' 假设API需要身份验证令牌}response = requests.get(url, headers=headers)print(response.text) 输出响应内容
传递查询参数
使用`params`参数传递URL中的查询参数,这通常用于GET请求。参数应该是一个字典,`requests`库会自动将这些参数编码并附加到URL上。例如:

import requestsurl = 'http://www.baidu.com'params = {'wd': 'python','ie': 'utf-8' 可选:指定编码类型}response = requests.get(url, params=params)print(response.text) 输出响应内容
如果需要同时设置请求头和查询参数,可以结合使用:
import requestsurl = 'http://www.example.com/search'headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)','Accept-Language': 'zh-CN,zh;q=0.9'}params = {'q': 'Python 编程','lang': 'zh'}response = requests.get(url, headers=headers, params=params)print(response.text) 输出响应内容
以上示例展示了如何在请求头中设置自定义字段以及在URL中传递查询参数。
