requests请求参数
时间: 2024-12-27 14:20:13 浏览: 49
### 使用 Python `requests` 库发送带参数的 HTTP 请求
#### 发送带有查询参数的 GET 请求
为了通过 `requests.get()` 方法发送带有查询参数的 GET 请求,可以定义一个字典来存储这些参数并将其作为 `params` 参数传递给该函数。
```python
import requests
url = 'https://example.com/api'
query_params = {'name': 'John', 'age': 30}
response = requests.get(url, params=query_params)
print(response.url) # 打印实际访问URL以确认参数已附加到URL上
if response.status_code == 200:
print(response.json())
else:
print('Request failed with status code:', response.status_code)
```
此代码片段展示了如何构建包含两个键值对 (`name=John`, `age=30`) 的查询字符串,并附加上述 URL 后面进行请求[^1]。
#### 发送 POST 请求并带上表单数据或其他类型的负载
当需要提交 HTML 表单或者其他形式的数据时,则应该使用 `data` 或者 `json` 关键字参数。对于 JSON 数据来说,通常会更倾向于使用后者因为它能自动处理序列化过程。
```python
import json
import requests
post_url = "https://example.com/post"
form_data = {"username": "test_user", "password": "secure_password"}
headers = {
'Content-Type': 'application/json',
}
# 如果服务器期望接收JSON格式的数据则应如此操作:
response_post_json = requests.post(post_url, headers=headers, json=form_data)
# 对于传统的HTML表单编码方式则是这样:
response_post_form = requests.post(post_url, data=form_data)
if response_post_json.status_code == 200 or response_post_form.status_code == 200:
print("Data sent successfully.")
else:
print("Failed to send data.", end=" ")
if not response_post_json.ok:
print(f"Error sending JSON payload: {response_post_json.status_code}")
elif not response_post_form.ok:
print(f"Error sending form-encoded data: {response_post_form.status_code}")
```
这段例子说明了两种不同的情况——一种是将数据作为 JSON 负载传输;另一种是以标准 Web 表单的方式传送[^4]。
#### 添加自定义头部信息 (如 Token 认证)
有时 API 需要验证客户端身份,在这种情况下可以在请求头中加入认证令牌(Token),这同样适用于 GET 和 POST 请求:
```python
auth_token = "your_auth_token_here"
get_headers_with_token = {'Authorization': f'Bearer {auth_token}'}
post_headers_with_token = {'Authorization': f'Bearer {auth_token}', 'Content-Type': 'application/json'}
secured_get_response = requests.get(secure_api_endpoint, headers=get_headers_with_token)
secured_post_response = requests.post(secure_api_endpoint, headers=post_headers_with_token, json=payload)
for resp in [secured_get_response, secured_post_response]:
if resp.status_code != 200:
print(f'Secure request returned non-ok status ({resp.status_code})')
else:
try:
result = resp.json()
print(result)
except ValueError as e:
print(e)
```
上述代码段显示了怎样利用 Bearer Tokens 来保护 API 请求的安全性[^2]。
阅读全文
相关推荐

















