local http = require("socket.http") local ltn12 = require("ltn12") local M = {} M.timeout = 60*5 M.get = function(url,headers) http.TIMEOUT = M.timeout local response_body = {} local res, status_code, response_headers, status_text = http.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(response_body) } if not res then return false,"err_http_get1,status_code:"..(status_code or "N/A")..",status_text:"..(status_text or "N/A")..",response_body:"..table.concat(response_body) end if status_code ~= 200 then return false,"err_http_get2,status_code:"..(status_code or "N/A")..",status_text:"..(status_text or "N/A")..",response_body:"..table.concat(response_body) end return true,table.concat(response_body) end M.post = function(url,headers,body) http.TIMEOUT = M.timeout local response_body = {} headers["Content-Length"] = tostring(#body) local res, status_code, response_headers, status_text = http.request{ url = url, method = "POST", headers = headers, source = ltn12.source.string(body), sink = ltn12.sink.table(response_body) } if not res then return false,"err_http_post,status_code:"..(status_code or "N/A")..",status_text:"..(status_text or "N/A")..",response_body:"..table.concat(response_body) end if status_code ~= 200 then return false,"err_http_post,status_code:"..(status_code or "N/A")..",status_text:"..(status_text or "N/A")..",response_body:"..table.concat(response_body) end return true,table.concat(response_body) end M.delete = function(url,headers) http.TIMEOUT = M.timeout local response_body = {} local res, status_code, response_headers, status_text = http.request{ url = url, method = "DELETE", headers = headers, sink = ltn12.sink.table(response_body) } if not res then return false,"err_http_delete,status_code:"..(status_code or "N/A")..",status_text:"..(status_text or "N/A")..",response_body:"..table.concat(response_body) end if status_code ~= 200 then return false,"err_http_delete,status_code:"..(status_code or "N/A")..",status_text:"..(status_text or "N/A")..",response_body:"..table.concat(response_body) end return true,table.concat(response_body) end -- 生成 A=B&C=D 的格式 M.build_query = function(params) local query = {} for k, v in pairs(params) do table.insert(query, k .. "=" .. v) end return table.concat(query, "&") end return M