为什么 Web 服务器会回复 301 状态码和准确的请求目标地址?

我正试图通过 lua 和 luasec 使用 https 从 Web 服务器中检索页面。对于大多数页面,我的脚本都按预期工作,但如果资源包含特殊字符(比如,'é),我会收到 301 响应,进入一个循环中。

让这个代码片段来说明我的困境(实际服务器细节已省略以保护无辜):

local https = require "ssl.https"
local prefix = "https://www.example.com"
local suffix = "/S%C3%A9ance"
local body,code,headers,status = https.request(prefix .. suffix)
print(status .. " - GET was for \"" .. prefix .. suffix .. "\"")
print("headers are " .. myTostring(headers))
print("body is " .. myTostring(body))
if suffix == headers.location then
    print("equal")
else
    print("not equal")
end
local body,code,headers,status = https.request(prefix .. headers.location)
print(status .. " - GET was for \"" .. prefix .. suffix .. "\"")

这会导致悖论

HTTP/1.1 301 Moved Permanently - GET was for "https://www.example.com/S%C3%A9ance" headers are { ["content-type"]="text/html; charset=UTF-8";["set-cookie"]="PHPSESSID=e80oo5dkouh8gh0ruit7mj28t6; path=/";["content-length"]="0";["connection"]="close";["date"]="Wed, 15 Mar 2017 19:31:24 GMT";["location"]="S%C3%A9ance";} body is "" equal HTTP/1.1 301 Moved Permanently - GET was for "https://www.example.com/S%C3%A9ance"

如何才能使用尽可能少的依赖关系在 lua 中检索这些难以捕捉的页面呢?

点赞
用户7716814
用户7716814

显而易见的是,可能请求的 URL 与实际位置不同。

如果您遇到类似的问题,请深入检查您的外部库,确保它们的功能与您想象的一样。

在这种情况下,Luasocket 对 URL 进行了 urldecode,然后对其进行了 urlencode,因此最终的请求并不是看起来的那样。

2017-03-17 00:37:10