0

我正在尝试使用 Lua Socket 进行 http 获取:

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
4

1 回答 1

4

Here is a runnable version of your code example (that exhibit the problem you described):

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

If you read the error page returned, you can see that its title is Heroku | No such app.

The reason for that is that the Heroku router only works when a Host header is provided. The easiest way to do it is to use the actual HTTP module of LuaSocket instead of TCP directly:

local http = require "socket.http"
local s, status, headers = http.request("http://warm-harbor-2019.herokuapp.com/get_tweets")
print(s)

If you cannot use socket.http you can pass the Host header manually:

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)

With my version of LuaSocket, s will be nil, status will be "closed" and partial will contain the full HTTP response (with headers etc).

于 2014-05-18T18:27:24.053 回答