Skip to content

Instantly share code, notes, and snippets.

@seveniu
Last active August 29, 2015 14:05
Show Gist options
  • Save seveniu/ffcf84b1071800e6dcb3 to your computer and use it in GitHub Desktop.
Save seveniu/ffcf84b1071800e6dcb3 to your computer and use it in GitHub Desktop.
lua socket http 请求
local http=require("http")
local httpRequest = {}
function httpRequest:new()
local obj = {}
self.__index = self
return setmetatable(obj,self)
end
function httpRequest:getInstance()
if nil == self.instance then
self.instance = self:new()
end
return self.instance
end
function httpRequest:get(url,data,callback)
self:send("GET",url,data,callback)
end
function httpRequest:post(url,data,callback)
self:send("POST",url,data,callback)
end
function httpRequest:send(requestType,url,data,callback)
if(type(data) == "table") then
data = self:dataParse(data)
end
local request_body = data
print(request_body)
local response_body = {}
local res, code, response_headers = http.request{
url = url,
method = requestType,
headers =
{
["Content-Type"] = "application/x-www-form-urlencoded";
["Content-Length"] = #request_body;
},
source = ltn12.source.string(request_body),
sink = ltn12.sink.table(response_body),
}
local responseText
if type(response_body) == "table" then
responseText = table.concat(response_body)
else
responseText = "Not a table:", type(response_body)
end
callback(responseText)
end
-- 数据转换,将请求数据由 table 型转换成 string,参数:table
function httpRequest:dataParse(data)
if "table" ~= type(data) then
print("data is not a table")
return nil
end
local tmp = {}
for key, value in pairs(data) do
table.insert(tmp,key.."="..value)
end
local newData = ""
for i=1,#tmp do
newData = newData..tostring(tmp[i])
if i<#tmp then
newData = newData.."&&"
end
end
-- print("------- data "..newData)
return newData
end
--local request_body = [[login=user&password=123]]
--local response_body = {}
--
--local res, code, response_headers = http.request{
-- url = "http://httpbin.org/post",
-- 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("res:"..res)
--print("code"..code)
--
--if type(response_headers) == "table" then
-- for k, v in pairs(response_headers) do
-- print(k, v)
-- end
--end
--
--print("Response body:")
--if type(response_body) == "table" then
-- print(table.concat(response_body))
--else
-- print("Not a table:", type(response_body))
--end
return httpRequest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment