Joh*_*oga 5 https lua luasocket luasec
我正在尝试从我的 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)
Run Code Online (Sandbox Code Playgroud)
但是在 HTTPS 页面上,我收到以下错误。
您的浏览器发送了此服务器无法理解的请求。
原因:您对启用 SSL 的服务器端口使用纯 HTTP。
请改用 HTTPS 方案访问此 URL。
现在我做了我的研究,有些人建议使用 Luasec,但无论我尝试了多少,我都无法让它工作。此外,Luasec 的库比我正在寻找的要复杂一些。我试图获取的页面仅包含一个 json 对象,如下所示:
{
"value" : "false",
"timestamp" : "2017-03-06T14:40:40Z"
}
Run Code Online (Sandbox Code Playgroud)
我的博客文章中有几个luasec 示例;假设你已经安装了 luasec,那么简单的事情应该可以工作:
require("socket")
local https = require("ssl.https")
local body, code, headers, status = https.request("https://www.google.com")
print(status)
Run Code Online (Sandbox Code Playgroud)
将 http 请求发送到端口 443(不使用 luasec)是行不通的,因为 http 库不知道需要发生的任何握手和加密步骤。
如果您有特定的错误,您应该描述它们是什么,但以上应该有效。
试试这个代码:
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) )
Run Code Online (Sandbox Code Playgroud)
要获取 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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5095 次 |
| 最近记录: |