httpclient.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. local http = require("socket.http")
  2. local ltn12 = require("ltn12")
  3. local cjson = require("cjson")
  4. require("app.app")
  5. local M = {}
  6. M.get = function(url,headers)
  7. local response_body = {}
  8. local res, status_code, response_headers, status_text = http.request{
  9. url = url,
  10. method = "GET",
  11. headers = headers,
  12. sink = ltn12.sink.table(response_body)
  13. }
  14. if not res then
  15. 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)
  16. end
  17. if status_code ~= 200 then
  18. 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)
  19. end
  20. return true,table.concat(response_body)
  21. end
  22. M.post = function(url,headers,body)
  23. local response_body = {}
  24. headers["Content-Length"] = tostring(#body)
  25. local res, status_code, response_headers, status_text = http.request{
  26. url = url,
  27. method = "POST",
  28. headers = headers,
  29. source = ltn12.source.string(body),
  30. sink = ltn12.sink.table(response_body)
  31. }
  32. if not res then
  33. 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)
  34. end
  35. if status_code ~= 200 then
  36. 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)
  37. end
  38. return true,table.concat(response_body)
  39. end
  40. M.delete = function(url,headers)
  41. local response_body = {}
  42. local res, status_code, response_headers, status_text = http.request{
  43. url = url,
  44. method = "DELETE",
  45. headers = headers,
  46. sink = ltn12.sink.table(response_body)
  47. }
  48. if not res then
  49. 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)
  50. end
  51. if status_code ~= 200 then
  52. 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)
  53. end
  54. return true,table.concat(response_body)
  55. end
  56. -- 生成 A=B&C=D 的格式
  57. M.build_query = function(params)
  58. local query = {}
  59. for k, v in pairs(params) do
  60. table.insert(query, k .. "=" .. v)
  61. end
  62. return table.concat(query, "&")
  63. end
  64. return M