Get HTTPS page content with Lua
我正在尝试从我的lua代码访问网页的内容。以下代码适用于非HTTPS页面
1 2 3 4 5 6 | local http=require("socket.http") body,c,l,h = http.request("http://www.example.com:443") print("status line",l) print("body",body) |
但是在HTTPS页面上,出现以下错误。
Your browser sent a request that this server could not understand.
Reason: You're speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.
现在我进行了研究,有人建议使用Luasec,但是无论我尝试了多少,我都无法使它正常工作。而且,Luasec的库比我要寻找的要复杂一些。我正在尝试获取的页面仅包含一个json对象,如下所示:
1 2 3 4 | { "value" :"false", "timestamp" :"2017-03-06T14:40:40Z" } |
我的博客文章中有几个luasec示例;假设您已经安装了luasec,则应执行以下简单的操作:
1 2 3 4 | require("socket") local https = require("ssl.https") local body, code, headers, status = https.request("https://www.google.com") print(status) |
将http请求发送到端口443(不使用luasec)将无法正常工作,因为http库不知道需要进行任何握手和加密步骤。
如果您有特定的错误,则应描述它们是什么,但以上内容应能起作用。
尝试此代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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'
1 2 3 4 5 6 7 8 9 10 11 | 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) } |