使用Python的http.client模块发送HTTP请求并进行错误处理
发布时间:2024-01-19 21:25:53
Python 的 http.client 模块提供了发送 HTTP 请求的功能。它是一个低级别模块,可用于与网络服务器进行通信。下面是使用 http.client 模块发送 HTTP 请求并进行错误处理的示例:
import http.client
import json
def send_http_request(url, method, headers=None, body=None):
try:
# 解析请求 URL 获取主机和路径
host, path = http.client.urlsplit(url)[1:3]
# 创建 HTTP 连接
conn = http.client.HTTPConnection(host)
# 发送请求
conn.request(method, path, headers=headers, body=body)
# 获取响应
response = conn.getresponse()
# 打印响应状态码和消息
print(f"Status: {response.status} {response.reason}")
# 读取响应内容
data = response.read()
# 关闭连接
conn.close()
# 返回响应内容
return data.decode('utf-8')
except http.client.HTTPException as e:
print(f"HTTPException: {e}")
except ConnectionError as e:
print(f"ConnectionError: {e}")
except Exception as e:
print(f"Exception: {e}")
return None
# 发送 GET 请求
url = "http://api.example.com/data"
response = send_http_request(url, "GET")
if response:
json_response = json.loads(response)
print(json_response)
# 发送 POST 请求
payload = json.dumps({"key": "value"})
headers = {"Content-Type": "application/json"}
response = send_http_request(url, "POST", headers=headers, body=payload)
if response:
json_response = json.loads(response)
print(json_response)
在上面的例子中,我们定义了一个 send_http_request 函数来发送 HTTP 请求。它接受以下参数:
- url:请求的 URL
- method:请求方法,可以是 "GET"、"POST" 等
- headers:请求头字典
- body:请求体内容
在函数内部,我们使用 http.client.urlsplit 函数解析请求的 URL,获取主机和路径。然后,我们使用 http.client.HTTPConnection 创建一个 HTTP 连接。通过调用 conn.request 方法,我们发送了请求。然后,我们使用 conn.getresponse 方法获取响应。我们通过调用 response.read 读取响应内容,并使用 response.status 和 response.reason 获取响应状态码和消息。最后,我们关闭连接并返回响应内容。
在异常处理中,我们捕获了 http.client.HTTPException、ConnectionError 和其他异常,并打印了相应的错误消息。如果发生异常,则返回 None。
上面的示例演示了如何发送 GET 和 POST 请求,并用json模块解析响应内容。你可以根据自己的需求定制函数和处理方式。
