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

Lua处理HTTP 301重定向并保存接口返回PNG图像的问题

Lua调用HTTPS图表接口与PNG提取解决方案

1 修复HTTPS请求返回nil问题

核心原因

HTTPS请求全返回nil是两个常见问题导致:

  • luasec默认开启SSL证书校验,没有指定CA证书路径时会校验失败直接终止请求
  • 目标站点有反爬策略,缺少浏览器标识的请求会被直接拦截

修复后代码

local https = require("ssl.https")
local ltn12 = require "ltn12"
-- 自定义请求头,模拟Chrome浏览器访问
local request_headers = {
    ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    ["Accept"] = "image/png,image/*;q=0.8,*/*;q=0.5"
}
local r = {} -- 存储返回的二进制内容
local result, code, headers, status = https.request{
    url = "https://www.chartgo.com/create.do?charttype=line&width=650&height=650&chrtbkgndcolor=white&gridlines=1&labelorientation=horizontal&title=Fdsfsdfdsfsdfsdfsdf&subtitle=Qrqwrwqrqwrqwr&xtitle=Cbnmcbnm&ytitle=Ghjghj&source=Hgjghj&fonttypetitle=bold&fonttypelabel=normal&gradient=1&max_yaxis=&min_yaxis=&threshold=&labels=1&xaxis1=Jan%0D%0AFeb%0D%0AMar%0D%0AApr%0D%0AMay%0D%0AJun%0D%0AJul%0D%0AAug%0D%0ASep%0D%0AOct%0D%0ANov%0D%0ADec&yaxis1=20%0D%0A30%0D%0A80%0D%0A90%0D%0A50%0D%0A30%0D%0A60%0D%0A50%0D%0A40%0D%0A50%0D%0A10%0D%0A20&group1=Group+1&viewsource=mainView&language=en§ionSetting=§ionSpecific=§ionData=",
    sink = ltn12.sink.table(r),
    headers = request_headers,
    -- 关闭SSL证书校验,调试用;生产环境建议指定cafile参数为系统CA证书路径
    verify = "none",
    protocol = "any"
}
-- 调试输出
print("请求状态码:".. tostring(code))
print("请求状态描述:".. tostring(status))

2 PNG图像提取方案

请求成功(状态码为200)后,table.concat(r, "")得到的就是完整的PNG二进制数据,可直接用于后续处理:

保存为本地PNG文件示例

if code == 200 then
    local png_data = table.concat(r, "")
    -- 二进制写模式打开文件
    local file = io.open("output_chart.png", "wb")
    if file then
        file:write(png_data)
        file:close()
        print("图表已保存为output_chart.png")
    end
    -- 若需要在内存中直接处理,直接使用png_data变量即可
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:36:00