httpbin.org 是一个用于测试HTTP请求的免费服务,非常适合学习和测试Requests库。下面将展示Requests库的各种用法示例,全部基于httpbin.org
基本功能示例
这些示例涵盖了Requests库的大部分常用功能,全部基于httpbin.org进行测试。可以根据需要修改和扩展这些代码示例。
1. 基本请求方法
import requests
# GET请求
response = requests.get('https://httpbin.org/get')
print("GET请求响应:", response.json())
# POST请求
response = requests.post('https://httpbin.org/post', data={'key': 'value'})
print("POST请求响应:", response.json())
# PUT请求
response = requests.put('https://httpbin.org/put', data={'key': 'value'})
print("PUT请求响应:", response.json())
# DELETE请求
response = requests.delete('https://httpbin.org/delete')
print("DELETE请求响应:", response.json())
# HEAD请求
response = requests.head('https://httpbin.org/get')
print("HEAD请求头信息:", response.headers)
# OPTIONS请求
response = requests.options('https://httpbin.org/get')
print("OPTIONS请求响应:", response.headers)
2. 传递参数
# 查询字符串参数
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print("带参数的GET请求:", response.json())
# 表单数据
data = {'username': 'testuser', 'password': 'testpass'}
response = requests.post('https://httpbin.org/post', data=data)
print("表单POST请求:", response.json())
# JSON数据
json_data = {'name': 'John', 'age': 30, 'city': 'New York'}
response = requests.post('https://httpbin.org/post', json=json_data)
print("JSON POST请求:", response.json())
3. 请求头设置
headers = { 'User-Agent': 'MyApp/1.0', 'Accept': 'application/json', 'X-Custom-Header': 'HelloWorld' } response = requests.get('https://httpbin.org/headers', headers=headers) print("自定义请求头:", response.json())
4. Cookies操作
# 发送Cookies cookies = {'session_id': '12345', 'token': 'abcdef'} response = requests.get('https://httpbin.org/cookies', coo