2012-06-23 59 views
4

我们的应用程序需要使用Lua从网站获取一些数据。但网站需要认证(如谷歌的登录方法)。使用lua模拟登录

我想使用LuaSocket库,但我找不到完整的代码示例,所以我只知道我需要做什么。

我知道http.request()有第二个可选参数,它允许我发送POST数据,并且我也可以使用完整的语法来指定POST方法和要发送的数据,但我有不知道数据应该是什么格式,以及它应该是什么样子。表?串?什么?

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

有人可以帮助我。给我一个完整的示例登录谷歌使用卢阿?

任何帮助,将大大赞赏。非常感谢。

+0

你尝试过这么远吗?检查[luasocket标签]中的其他问题(http://stackoverflow.com/questions/tagged/luasocket) – hjpotter92

+0

感谢您的建议。 – ms2008

回答

3

如果网站不使用HTTP基本身份验证,但使用HTML表单autentificate用户,你必须到现场开发商没有进入,最好的办法弄清楚是怎么回事是什么浏览器来偷看确实。

启动您的Firebug或Google Chrome Developer Tools或某个HTTP调试代理。

在浏览器中打开该网站,登录并查看浏览器做了什么请求,以及该网站的回复是什么。你必须在你的程序中模仿相同的请求。

请注意,很可能该网站将要求您在随后的请求中发送会话信息以保持身份验证。它可能是一个cookie(或几个)和/或一个GET参数。再次看看浏览器的功能和模仿。

至于格式 - 在网上搜索例子,有几个。

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

请注意,示例中使用的网址即将过期。只需在http://requestb.in/创建您自己的。在浏览器中打开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 
+0

感谢您的评论。我知道该网站使用网络形式来验证用户,并且我有帐户来访问它。因此,我应该怎么做,我使用Google搜索,但没有在卢阿找到任何样本。 – ms2008

+0

你知道你需要发送什么数据吗? –

+0

另外,请注意,如果网站使用HTTPS,你不能使用'luasocket',你必须使用'luasec'(它具有兼容的API)。 –