TLSv1弃用后HTTPS文件传输失效,sendString配置求助
问题分析与修复方案
核心问题
- 错误使用POST请求:Dropbox带
dl=1参数的下载链接是通过GET请求直接获取文件的,不需要发送请求体,当前代码误用POST方法,还试图设置无关的请求体参数sendString,这是连接重置的关键原因。 sendString未定义:代码引用了未声明的sendString变量,会直接抛出错误;同时POST请求对应的content-type、content-length请求头以及source参数都是多余配置。- 响应处理逻辑不一致:配置了
sink = ltn12.sink.table(response_body)将响应写入表,但后续仍试图用response变量写入文件,会导致文件内容异常。
修复后的代码
--downloadfile - downloads a file to the gateway --Returns: --result - result of this function --filename - name of file --fulllocalpath - path where file is stored locally --resultstr - status info local function downloadfile(filename, url, isbinary) local string1 = " Downloading file from: " .. url --print("UMONIoT","INFO", string1) -- retrieve the content of a URL local rawname = url local fname = filename --rawname:match("[%w+.%w]+$") local fulllocalpath = FTPATH .. fname log("UMONIoT","INFO", "Starting download to local directory: " .. fulllocalpath) local resultstr = "Starting download to local directory: " .. fulllocalpath .."\r" local response_body = {} local response, resultcode, respheaders, respstatus if rawname:match("https://") then local https = require'ssl.https' local ltn12 = require("ltn12") -- 显式导入ltn12库 -- 使用GET请求,配置TLSv1.2(或v1.3) response, resultcode, respheaders, respstatus = https.request{ url = rawname, protocol = 'tlsv1_2', -- 若ssl库支持,可改为'tlsv1_3' method = 'GET', -- 改为GET请求 sink = ltn12.sink.table(response_body) -- 将响应写入response_body表 } log("UMONIoT","INFO", "File download response [" .. tostring(response) .. "].") log("UMONIoT","INFO", "File download resultcode [" .. tostring(resultcode) .. "].") log("UMONIoT","INFO", "File download respstatus [" .. tostring(respstatus) .. "].") -- 将response_body表拼接成字符串,用于后续写入文件 response = table.concat(response_body) else local http = require("socket.http") response, resultcode = http.request(url) end if resultcode ~= 200 then log("UMONIoT","ERROR", "Failed to download file. Error code [" .. tostring(resultcode) .. "].") resultstr = resultstr .. "Failed to download file. Error code [" .. tostring(resultcode) .. "]." return false, nil, nil, resultstr else -- save the content to a file if isbinary == true then local f = assert(io.open(fulllocalpath, 'wb')) -- open in "binary" mode f:write(response) f:close() else local f = assert(io.open(fulllocalpath, 'w')) if fname:match("SETUP") then local newresponse = updateIPandCredentials(response) f:write(newresponse) f:close() else f:write(response) f:close() end end log("UMONIoT","INFO", "Successfully downloaded file: " .. fname .. " to gateway.") resultstr = resultstr .. "Successfully downloaded file: " .. fname .. " to gateway." return true, filename ,fulllocalpath, resultstr end end
关键调整说明
- 请求方法改为
GET,移除所有与请求体相关的冗余配置。 - 显式导入
ltn12库,避免隐式依赖导致的运行错误。 - 将
response_body表拼接为字符串,保证后续写入文件的内容正确。 - 可选:若使用的
ssl库支持TLSv1.3,可将protocol参数改为'tlsv1_3'。
内容的提问来源于stack exchange,提问作者Terry Z.
相关产品推荐
相关产品推荐

