Lua套接字连接错误

我正在尝试使用 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

我期望s返回一条推文,因为我执行的 GET 请求应该返回一条推文。但是,我得到的结果是:

http/1.1 404 object not found
点赞
用户204011
用户204011

以下是你提供代码示例的可运行版本(展示了你描述的问题):

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

如果你读取返回的错误页面,你会发现它的标题是 _Heroku | No such app_。

原因是 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)

如果你无法使用 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)

使用我的版本的 LuaSocket,s 将为 nilstatus 将为 "closed",而 partial 将包含完整的 HTTP 响应(包括头部等)。

2014-05-18 18:27:24