httpclient.lua 2.5 KB

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