import os
import requests
import chardet
from urllib3.exceptions import InsecureRequestWarning

# 禁用 InsecureRequestWarning 警告
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

def download_file(url, save_directory, filename):
    # 确保保存目录存在
    if not os.path.exists(save_directory):
        os.makedirs(save_directory)

    # 构建完整的本地文件路径
    local_filepath = os.path.join(save_directory, filename)

    try:
        # 发送HTTP GET请求以获取文件数据
        response = requests.get(url, verify=False)  # 禁用SSL验证

        # 检查响应状态码是否为200（OK）
        if response.status_code == 200:
            # 自动检测文件编码
            detected_encoding = chardet.detect(response.content)['encoding']
            print(f"检测到的编码: {detected_encoding}")

            # 将响应内容解码为字符串
            content = response.content.decode(detected_encoding)

            # 打开本地文件以文本写入模式，并将响应内容写入文件
            with open(local_filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"文件已成功下载并保存为 {local_filepath}")
        else:
            print(f"无法下载文件，状态码: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"请求过程中出现错误: {e}")

if __name__ == "__main__":
    # 使用示例
    url = "https://192.168.5.218:8443/media/file/check.txt"
    save_directory = r"D:\GithubData\自动化\ubains-module-test\预定系统\reports"  # 指定保存目录
    filename = "check.txt"
    download_file(url, save_directory, filename)