使用Lua进行模拟登录

我们的应用程序需要使用 Lua 从网站获取一些数据,但该网站需要进行身份验证(类似于 Google 的登录方法)。

我正在尝试使用 LuaSocket 库,但是我找不到代码的完整示例,所以我只知道我需要做什么的一半。

我知道 http.request() 有一个可选的第二个参数,可以让我发送 POST 数据,我也可以使用完整的语法来指定 POST 方法和要发送的数据,但我不知道数据应该采用什么格式,长什么样子。表格?字符串?什么?

我也知道我需要设置内容类型和内容长度 - 但我不知道这些值应该是什么,也不知道如何找出它们。我不知道该选什么和该写什么。

有人能帮忙吗?给我一个使用 Lua 登录 Google 的完整示例吗?

非常感谢任何帮助。非常感谢。

点赞
用户6236
用户6236

如果网站不使用HTTP基本认证,而是使用HTML表单进行用户认证,并且您无法访问网站开发者,最好的方法是窥视浏览器的操作。

打开Firebug或Google Chrome开发工具,或使用某个HTTP调试代理。

在浏览器中打开网站,登录,并查看浏览器完成哪些请求以进行身份验证,以及网站的回复。您必须在程序中模拟相同的请求。

请注意,很可能网站需要您在随后的请求中发送会话信息以保持已认证状态。它可能是一个cookie(或多个),或者是一个GET参数。同样,查看浏览器的操作并进行模拟。

至于格式,请在网上搜索示例,有一些。

更新:好的,这里是一个例子。

请注意,示例中使用的URL将很快过期。只需在 [http://requestb.in/](http://requestb.in/)上创建自己的URL。在浏览器中打开 [http://requestb.in/vbpkxivb?inspect](http://requestb.in/vbpkxivb?inspect)以查看数据。不要向此服务发送实际的登录名和密码!

require 'socket.http'

local request_body = [[login=user&password=123]]

local response_body = { }

local res, code, response_headers = socket.http.request
{
  url = "http://requestb.in/vbpkxivb";
  method = "POST";
  headers =
  {
    ["Content-Type"] = "application/x-www-form-urlencoded";
    ["Content-Length"] = #request_body;
  };
  source = ltn12.source.string(request_body);
  sink = ltn12.sink.table(response_body);
}

print("Status:", res and "OK" or "FAILED")
print("HTTP code:", code)
print("Response headers:")
if type(response_headers) == "table" then
  for k, v in pairs(response_headers) do
    print(k, ":", v)
  end
else
  -- Would be nil, if there is an error
  print("Not a table:", type(response_headers))
end
print("Response body:")
if type(response_body) == "table" then
  print(table.concat(response_body))
else
  -- Would be nil, if there is an error
  print("Not a table:", type(response_body))
end
print("Done dumping response")

预期输出:

Status: OK
HTTP code:      200
Response headers:
date    :       Sat, 23 Jun 2012 07:49:13 GMT
content-type    :       text/html; charset=utf-8
connection      :       Close
content-length  :       3
Response body:
ok

Done dumping response
2012-06-23 06:45:26