059. 编写一个函数,实现简单的HTTP客户端功能
以下是一个简单的 Python 函数,使用 requests
库实现基本的 HTTP 客户端功能。requests
是 Python 中一个非常流行的 HTTP 库,可以方便地发送 HTTP 请求。
示例代码
import requests
def simple_http_client(url, method='GET', headers=None, data=None):
"""
简单的 HTTP 客户端函数
:param url: 请求的 URL
:param method: 请求方法,支持 GET、POST、PUT、DELETE 等,默认为 GET
:param headers: 请求头,字典格式,默认为空
:param data: 请求体数据,字典格式(适用于 POST/PUT 等方法),默认为空
:return: 响应对象
"""
# 如果没有提供 headers,则初始化为空字典
if headers is None:
headers = {}
# 根据请求方法发送请求
try:
if method.upper() == 'GET':
response = requests.get(url, headers=headers)
elif method.upper() == 'POST':
response = requests.post(url, headers=headers, data=data)
elif method.upper() == 'PUT':
response = requests.put(url, headers=headers, data=data)
elif method.upper() == 'DELETE':
response = requests.delete(url, headers=headers)
else:
raise ValueError(f"不支持的请求方法:{method}")
except requests.exceptions.RequestException as e:
print(f"请求失败:{e}")
return None
return response
# 示例用法
if __name__ == "__main__":
# 发送 GET 请求
url = "https://jsonplaceholder.typicode.com/posts"
response = simple_http_client(url)
if response:
print("GET 请求响应状态码:", response.status_code)
print("GET 请求响应内容:", response.text)
# 发送 POST 请求
url = "https://jsonplaceholder.typicode.com/posts"
data = {
"title": "foo",
"body": "bar",
"userId": 1
}
response = simple_http_client(url, method='POST', data=data)
if response:
print("POST 请求响应状态码:", response.status_code)
print("POST 请求响应内容:", response.text)
代码说明
参数说明:
-
url
:请求的 URL。 -
method
:请求方法,默认为GET
,支持GET
、POST
、PUT
、DELETE
等。 -
headers
:请求头,以字典形式传入,例如{"Content-Type": "application/json"}
。 -
data
:请求体数据,适用于POST
和PUT
方法,以字典形式传入。
异常处理:使用 requests.exceptions.RequestException
捕获请求过程中可能出现的异常,例如网络问题、URL 错误等。
返回值:返回 requests.Response
对象,包含响应状态码、响应头、响应内容等信息。
示例输出
假设使用上述代码中的示例用法,输出可能如下:
GET 请求响应状态码: 200
GET 请求响应内容: [{"userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}...]
POST 请求响应状态码: 201
POST 请求响应内容: {"title": "foo", "body": "bar", "userId": 1, "id": 101}
注意事项
如果需要发送 JSON 格式的数据,可以将 data
参数替换为 json
参数,例如:
response = requests.post(url, headers=headers, json=data)
如果需要处理响应内容为 JSON 格式,可以使用 response.json()
方法解析响应内容。
在实际使用中,可能需要根据目标服务器的要求设置合适的请求头,例如 Content-Type
、Authorization
等。
视频讲解
BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)