脚本代码
python
import requests
import os
from urllib.parse import parse_qs, unquote
import re
# 准备 TAR 文件路径
tar_file_path = 'G:/gitcode/python_htt/浙江/开播/EBDT_10233000000000001030101012023111700000107.tar' # 替换为实际的 TAR 文件路径
assert os.path.isfile(tar_file_path), f"{tar_file_path} does not exist or is not a file."
# 请求参数
api_url = 'http://192.168.10.188:80/Emergency/Receive/ebd.htm' # 替换为实际的 API URL
headers = {
# "Content-Type": "application/x-tar"
# "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>" ,
# "Content-Length": "8555263" ,
# "Host": "192.168.10.188:80" ,
# "User-Agent": "PostmanRuntime/7.33.0" ,
# "Accept": "*/*" ,
# "Accept-Encoding": "gzip, deflate, br" ,
# "Connection": "keep-alive"
} # 根据 API 文档添加所需的请求头,如 Authorization、Content-Type 等
# 读取 TAR 文件
with open(tar_file_path, 'rb') as tar_file:
# 构造 multipart/form-data 数据
files = {'file': ('G:/gitcode/python_htt/浙江/开播/EBDT_10233000000000001030101012023111700000107.tar', tar_file)} # 键为 API 文档要求的文件字段名,通常为 'file'
# 发送 POST 请求
response = requests.post(api_url, headers=headers, files=files)
# 检查响应状态码
if response.status_code == 200:
print("TAR file download successful.")
# 从 Content-Disposition 响应头中提取文件名
content_disposition = response.headers.get('content-disposition', '')
match = re.search(r'filename=([^"]+)', content_disposition)
if match:
filename = match.group(1)
else:
print("Unable to extract filename from Content-Disposition header.")
# 解码文件名中的 URL 编码字符
filename = unquote(filename)
# 定义本地保存路径(基于提取的文件名)
local_tar_path = f'G:/gitcode/python_htt/浙江/开播/{filename}'
# 以二进制写模式创建本地文件
with open(local_tar_path, 'wb') as local_tar_file:
# 将响应内容写入本地文件
local_tar_file.write(response.content)
print(f"TAR file saved to {local_tar_path}")
else:
print(f"Failed to download TAR file. Response status code: {response.status_code}")
发送之后会在当前路径下生成响应包