python 实现http客户端 发送tat包,并存储返回的tar包

脚本代码 

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}")

发送之后会在当前路径下生成响应包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值