下面的代码是用来解析HTTP报文中包含的内容的。http_parse函数将http报文初步解析为三个部分,分别是起始行,headers和body。主要利用的是python标准库中的email模块。
代码语言:javascript复制from email import parser, policy
from email.message import Message
from typing import Any
ENTER = "n"
CLRF = "rn"
def http_parse(http_pkg:str) -> tuple[str, dict[str,str], Any]:
"""
http报文初步解析函数
参数:http报文字符串
返回:http起始行,headers, body
"""
res:tuple[str, dict[str,str], Any]
if ENTER in http_pkg: # 处理非CLRF分割的http报文
res = http_pkg_split(ENTER, http_pkg)
elif CLRF in http_pkg:
res = http_pkg_split(CLRF, http_pkg)
return res
def http_pkg_split(sep:str, http_pkg:str) -> tuple[str, dict[str,str], Any]:
"""
http报文分割函数
参数:http报文字符串,分割字符
返回:http起始行,headers, body
"""
tmp:list[str] = http_pkg.split(sep=sep, maxsplit=1)
start_line:str = tmp[0]
others:str = tmp[1] # 去除http报文起始行之后,剩余的内容应完全遵从MIME数据格式
# 指定policy为HTTP,使得遵循 RFC 2822以及当前的各种 MIME RFC(RFC 5322, RFC 2047)
p:parser.Parser = parser.Parser(policy=policy.HTTP)
msg:Message = p.parsestr(text=others, headersonly=False) # 解析header和body
headers:dict[str, str] = {}
for k, v in msg.items():
headers[k] = str(v)
body:Any = msg.get_payload()
return start_line, headers, body
if __name__ == "__main__":
http_pkg:str = """GET / HTTP/1.1
Host: petstore.swagger.io
Content-Length: 171705
Sec-Ch-Ua: "(Not(A:Brand";v="8", "Chromium";v="99"
Accept: application/json
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryUmjLZJ95KycutKTH
Sec-Ch-Ua-Mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36
Sec-Ch-Ua-Platform: "Linux"
Origin: https://petstore.swagger.io
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://petstore.swagger.io/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
------WebKitFormBoundaryUmjLZJ95KycutKTH
Content-Disposition: form-data; name="additionalMetadata"
111
------WebKitFormBoundaryUmjLZJ95KycutKTH--
"""
res = http_parse(http_pkg=http_pkg)
print(res)
参考资料
email — 电子邮件与 MIME 处理包