You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌入式Lua 5.1环境下HTTPS文件下载失败问题求助

Lua 5.1嵌入式环境HTTPS文件下载无返回问题

环境与问题说明

  • 问题并非Lua 5.1独有,核心限制是嵌入式实例无法安装模块,只能使用纯Lua文件/引用,无法借助luacurl这类工具
  • HTTP请求可正常返回200状态码并完成文件下载,但HTTPS请求无任何返回结果,目标URL均可通过浏览器正常访问
  • 单独调用HTTPS请求无输出,打印luasec版本返回0.4

示例代码

print("--------DOWNLOAD http---------")

local http = require("socket.http")
local body, code = http.request("http://pbs.twimg.com/media/CCROQ8vUEAEgFke.jpg")
print(code)
if not body then error(code) end
local f = assert(io.open('mnt/nas/webtest1.jpg', 'wb')) -- 二进制模式打开文件
f:write(body)
f:close()

print("--------DOWNLOAD https---------")

local https = require "ssl.https" -- luasec模块
local body, code = https.request("https://u.cubeupload.com/jbcooper/16146313918060.jpg")
print(code)
if not body then error(code) end
local f = assert(io.open('mnt/nas/webtest2.jpg', 'wb')) -- 二进制模式打开文件
f:write(body)
f:close()

测试结果

  • 单独执行以下代码无任何返回:
local https = require "ssl.https" -- luasec模块
print(https.request("https://u.cubeupload.com/jbcooper/16146313918060.jpg"))
  • 执行以下代码返回0.4:
local https     = require("ssl.https") 
local httpsVersion = string.sub(https._VERSION,1,3)
print (httpsVersion)

解决配置方案

luasec 0.4版本较陈旧,默认SSL配置可能不兼容目标服务器的TLS协议,需手动指定SSL参数:
修改HTTPS请求代码,使用带配置参数的table调用:

local https = require "ssl.https"
local ssl = require "ssl"

local params = {
    url = "https://u.cubeupload.com/jbcooper/16146313918060.jpg",
    sslctx = ssl.newcontext({
        protocol = "tlsv1_2", -- 指定服务器兼容的TLS版本(优先选择tlsv1_2)
        verify = "none"       -- 嵌入式环境若无CA根证书,临时关闭证书验证(生产环境建议配置合法证书)
    })
}

local body, code, headers, status = https.request(params)
print("状态码:", code, "状态信息:", status)

if body then
    local f = assert(io.open('mnt/nas/webtest2.jpg', 'wb'))
    f:write(body)
    f:close()
    print("文件下载完成")
else
    print("请求失败原因:", code)
end

额外注意事项

  1. 若嵌入式环境存在CA根证书文件,可将verify设为"peer",并添加cafile = "/path/to/ca-cert.pem"参数指向证书路径,提升请求安全性
  2. 若指定tlsv1_2仍失败,可尝试"tlsv1"或"sslv3"(需确认目标服务器支持对应协议)

内容的提问来源于stack exchange,提问作者nodecentral

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:05:24