requests用法大全
时间: 2023-10-10 07:08:32 浏览: 59
requests 中文文档
4星 · 用户满意度95%
requests是一个流行的Python库,用于发送HTTP请求。它提供了一种简单而优雅的方式来发送各种类型的HTTP请求。下面是requests的一些用法:
1. 发送GET请求:
```python
import requests
url = 'http://example.com/api/user/1'
response = requests.get(url)
print(response.status_code) # 状态码
print(response.headers) # 响应头
print(response.json()) # 响应体
```
2. 发送POST请求:
```python
import requests
url = 'http://example.com/api/user/create'
data = {'name': 'John', 'age': 25}
response = requests.post(url, data=data)
print(response.status_code) # 状态码
print(response.json()) # 响应体
```
3. 发送带有查询参数的请求:
```python
import requests
url = 'http://example.com/api/users'
params = {'page': 1, 'count': 10}
response = requests.get(url, params=params)
print(response.status_code) # 状态码
print(response.json()) # 响应体
```
4. 发送带有请求头的请求:
```python
import requests
url = 'http://example.com/api/user/1'
headers = {'Authorization': 'Bearer token'}
response = requests.get(url, headers=headers)
print(response.status_code) # 状态码
print(response.json()) # 响应体
```
5. 发送带有文件的请求:
```python
import requests
url = 'http://example.com/api/user/avatar'
files = {'avatar': open('avatar.jpg', 'rb')}
response = requests.post(url, files=files)
print(response.status_code) # 状态码
print(response.json()) # 响应体
```
6. 发送带有Cookies的请求:
```python
import requests
url = 'http://example.com/api/user/1'
cookies = {'session_id': '123'}
response = requests.get(url, cookies=cookies)
print(response.status_code) # 状态码
print(response.json()) # 响应体
```
以上是requests的一些基本用法,还有许多其他功能和参数,可以查看官方文档以获得更多信息。
阅读全文