使用Lua获取HTTPS页面内容

我正在尝试从我的Lua代码中访问网页的内容。以下代码适用于非HTTPS页面

local http=require("socket.http")

body,c,l,h = http.request("http://www.example.com:443")

print("status line",l)
print("body",body)

但在HTTPS页面上,我会遇到以下错误。

您的浏览器发送了一个服务器无法理解的请求。

原因:您使用普通的HTTP与启用SSL的服务器端口进行通信。

请改用HTTPS方案访问此URL。

现在,我正在进行调查,有些人建议使用Luasec,但无论我怎么努力,都无法让它工作。 Luasec是一个比我正在寻找的库更加复杂的库。我试图获取的页面仅包含一个如下的json对象:

{
  "value" : "false",
  "timestamp" : "2017-03-06T14:40:40Z"
}
点赞
用户7504558
用户7504558

尝试这个代码:

local https = require('ssl.https')
https.TIMEOUT= 10
local link = 'http://www.example.com'
local resp = {}
local body, code, headers = https.request{
                                url = link,
                                headers = { ['Connection'] = 'close' },
                                sink = ltn12.sink.table(resp)
                                 }
if code~=200 then
    print("Error: ".. (code or '') )
    return
end
print("Status:", body and "OK" or "FAILED")
print("HTTP code:", code)
print("Response headers:")
if type(headers) == "table" then
  for k, v in pairs(headers) do
    print(k, ":", v)
  end
end
print( table.concat(resp) )

要获取 json 文件,请在请求表中设置 MIME 类型: content_type = 'application/json'

 body, code, headers= https.request{
    url = link,
    filename = file,
    disposition  = 'attachment',         -- if attach
    content_type = 'application/json',
    headers = {
                ['Referer'] = link,
                ['Connection'] = 'keep-alive'
                    },
    sink = ltn12.sink.table(resp)
 }
2017-03-06 15:33:07
用户1442917
用户1442917

我在我的博客文章中有一些 luasec 示例;假设您已经安装了 luasec,那么如下简单的代码应该可以工作:

require("socket")
local https = require("ssl.https")
local body, code, headers, status = https.request("https://www.google.com")
print(status)

发送到端口 443 的 http 请求(不使用 luasec)是行不通的,因为 http 库不知道需要发生什么握手和加密步骤。

如果您有具体的错误,请描述它们,但上面的代码应该可以工作。

2017-03-06 15:33:11