Python编程:requests库示例(基于httpbin.org)

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值