使用requests库发送GET/POST请求

74 阅读1分钟

微信图片_20230808094553.pngrequests是Python中最流行的HTTP客户端库之一,以其简洁的API和人性化的设计著称。下面详细介绍如何使用requests发送GET和POST请求,并处理响应数据。

1. 发送GET请求****

GET请求通常用于从服务器获取数据,requests库提供了简单直观的接口:

python

 import requests
  
 # 基本GET请求
 response = requests.get('api.example.com/data')
 print(response.status_code) # 输出HTTP状态码
 print(response.text) # 输出响应内容
  
 # 带参数的GET请求
 params = {'key1': 'value1', 'key2': 'value2'}
 response = requests.get('api.example.com/search', params=params)
 # 实际请求URL会被转换为:api.example.com/search?key1…
  
 # 处理JSON响应
 data = response.json() # 自动将JSON响应解析为Python字典
 print(data['result'])

2. 发送POST请求****

POST请求通常用于向服务器提交数据:

python

 import requests
 import json
  
 # 表单数据POST
 form_data = {'username': 'admin', 'password': 'secret'}
 response = requests.post('api.example.com/login', data=form_data)
  
 # JSON数据POST
 json_data = {'name': 'John', 'age': 30}
 headers = {'Content-Type': 'application/json'}
 response = requests.post('api.example.com/users',
 data=json.dumps(json_data),
 headers=headers)
  
 # 更简单的方式(requests会自动设置Content-Type)
 response = requests.post('api.example.com/users', json=json_data)

requests库的简洁设计使得HTTP请求变得异常简单,同时提供了足够的功能满足复杂需求。无论是简单的API调用还是复杂的交互场景,requests都能高效处理。