Mat*_*ima 0 sockets lua luasocket
我正在尝试使用 Lua Socket 进行 http get:
local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
if client then
client:send("GET /get_tweets HTTP/1.0\r\n\r\n")
s, status, partial = client:receive(1024)
end
end
Run Code Online (Sandbox Code Playgroud)
我希望s是一条推文,因为我所做的 get 返回一条推文。但我得到:
http/1.1 404 object not found
Run Code Online (Sandbox Code Playgroud)
这是代码示例的可运行版本(显示您所描述的问题):
local socket = require "socket"
local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
if client then
client:send("GET /get_tweets HTTP/1.0\r\n\r\n")
local s, status, partial = client:receive(1024)
print(s)
end
Run Code Online (Sandbox Code Playgroud)
如果你阅读返回的错误页面,你可以看到它的标题是Heroku | 没有这样的应用程序。
原因是 Heroku 路由器仅在Host提供标头时才工作。最简单的方法是使用 LuaSocket 的实际 HTTP 模块而不是直接使用 TCP:
local http = require "socket.http"
local s, status, headers = http.request("http://warm-harbor-2019.herokuapp.com/get_tweets")
print(s)
Run Code Online (Sandbox Code Playgroud)
如果您无法使用,socket.http可以手动传递 Host 标头:
local socket = require "socket"
local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
client:send("GET /get_tweets HTTP/1.0\r\nHost: warm-harbor-2019.herokuapp.com\r\n\r\n")
local s, status, partial = client:receive(1024)
print(s, status, partial)
Run Code Online (Sandbox Code Playgroud)
对于我的 LuaSocket 版本,swill be nil、statuswill be"closed"和partialwill 包含完整的 HTTP 响应(带有标头等)。