curl可正常请求Sipgate身份认证接口,使用Lua socket发起请求返回301错误
问题根因与修正方案
核心问题定位
- 请求模块匹配错误:代码虽然引入了
ssl.https模块,但实际发起请求时调用的是纯明文HTTP的socket.http模块,全程没有走TLS加密的HTTPS通信流程。这也是你收到的301响应中Location字段异常带上https://api.sipgate.com:80/v2/account/的根本原因——纯HTTP模块默认固定走80端口发请求,完全不符合HTTPS的443端口通信规范,自然会触发服务端的强制异常跳转。 - 重定向处理逻辑缺失:curl默认会自动跟随301/302类重定向(等价于内置
-L参数行为),但Lua的socket.http/ssl.https模块默认不会自动跟踪重定向,收到301状态就直接把响应结果返回给调用方,不会主动请求Location字段指向的新地址。 - 接口路径规范不匹配:目标API的路由规则强制要求账户接口路径必须带末尾斜杠,即正确访问路径为
/v2/account/,少写末尾斜杠就会触发301跳转。
修正后的可用代码
local https = require "ssl.https" local mime = require("mime") local data = "" local username = "你的实际认证用户名" local password = "你的实际认证密码" -- 响应数据收集回调 local function collect(chunk) if chunk ~= nil then data = data .. chunk end return true end -- 实现简单的重定向跟随逻辑 local function request_with_redirect(request_config, max_redirect_count) max_redirect_count = max_redirect_count or 3 local current_config = request_config for _ = 1, max_redirect_count do -- 清空上一次的响应缓存,避免多次请求的数据拼接错乱 data = "" local ok, status_code, headers, status_text = https.request { method = current_config.method, url = current_config.url, headers = current_config.headers, sink = collect } -- 遇到重定向状态码,更新请求地址进入下一轮循环 if status_code == 301 or status_code == 302 then current_config.url = headers.location else return ok, status_code, headers, status_text end end return nil, "重定向次数超过允许上限" end -- 发起实际请求 local ok, statusCode, headers, statusText = request_with_redirect { method = "GET", -- 路径补全末尾斜杠,匹配服务端路由规则 url = "https://api.sipgate.com/v2/account/", headers = { ["Accept"] = "application/json", -- 清理base64编码可能带出的换行符,避免认证头格式错误 ["Authorization"] = "Basic " .. (mime.b64(username .. ":" .. password):gsub("%s+", "")), }, } -- 调试输出 print("编码后的认证串", mime.b64(username .. ":" .. password)) print("请求执行状态", ok) print("响应状态码", statusCode) print("响应状态文本", statusText) print("接口返回数据", data)
额外校验点
- 确认本地安装的LuaSec(即
ssl.https模块)版本与当前Lua运行环境兼容,不存在TLS握手层面的适配问题。 - 服务端返回的带
:80端口的Location字段是纯HTTP请求触发的异常跳转结果,只要切换到正确的HTTPS模块、补全路径末尾斜杠,就不会再收到这种不符合HTTPS端口规范的跳转地址。
内容的提问来源于stack exchange,提问作者nodecentral
相关产品推荐
相关产品推荐

