6

我正在尝试从我的 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 页面上,我收到以下错误。

您的浏览器发送了此服务器无法理解的请求。
原因:您对启用 SSL 的服务器端口使用纯 HTTP。
请改用 HTTPS 方案访问此 URL。

现在我做了我的研究,有些人建议使用 Luasec,但无论我尝试了多少,我都无法让它工作。此外,Luasec 是一个比我正在寻找的更复杂的库。我试图获取的页面仅包含一个 json 对象,如下所示:

{
  "value" : "false",
  "timestamp" : "2017-03-06T14:40:40Z"
}
4

2 回答 2

7

我的博文中有几个luasec 示例;假设您已经安装了 luasec,如下所示的简单操作应该可以工作:

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

将 http 请求发送到端口 443(不使用 luasec)将不起作用,因为 http 库不知道需要发生的任何握手和加密步骤。

如果您有特定的错误,您应该描述它们是什么,但以上应该有效。

于 2017-03-06T15:33:11.773 回答
1

试试这个代码:

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-06T15:33:07.190 回答