httpLib.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. local httpLib = {}
  2. -- printTable(esphttp)
  3. -- {
  4. -- "init" = function: 42008586,
  5. -- "post_field" = function: 42008A58,
  6. -- "perform" = function: 42008BA0,
  7. -- "status_code" = function: 42008A0E,
  8. -- "content_length" = function: 42008C28,
  9. -- "read_response" = function: 42008992,
  10. -- "set_header" = function: 42008910,
  11. -- "get_header" = function: 420088A0,
  12. -- "cleanup" = function: 42008848,
  13. -- "is_done" = function: 420087EE,
  14. -- "go" = function: 42008B1E,
  15. -- "GET" = 0,
  16. -- "POST" = 1,
  17. -- "PUT" = 2,
  18. -- "PATCH" = 3,
  19. -- "DELETE" = 4,
  20. -- "EVENT_ON_FINISH" = 5,
  21. -- "EVENT_ERROR" = 0,
  22. -- "EVENT_DISCONNECTED" = 6,
  23. -- "EVENT_ON_DATA" = 4,
  24. -- }
  25. local methodTable = {
  26. GET = esphttp.GET,
  27. POST = esphttp.POST,
  28. PUT = esphttp.PUT,
  29. DELETE = esphttp.DELETE
  30. }
  31. function httpLib.request(method, url, head)
  32. local responseCode = 0
  33. local httpc = esphttp.init(methodTable[method], url)
  34. if httpc == nil then
  35. esphttp.cleanup(httpc)
  36. return false, responseCode, "create httpClient error"
  37. end
  38. if head ~= nil then
  39. for k, v in pairs(head) do
  40. esphttp.set_header(httpc, k, v)
  41. end
  42. end
  43. local ok, err = esphttp.perform(httpc, true)
  44. if ok then
  45. local response = ""
  46. while 1 do
  47. local result, c, ret, data = sys.waitUntil("ESPHTTP_EVT", 20000)
  48. -- log.info("ESPHTTP_EVT", result, c, ret, data)
  49. if result == false then
  50. esphttp.cleanup(httpc)
  51. return false, responseCode, "wait for http response timeout"
  52. end
  53. if c == httpc then
  54. if esphttp.is_done(httpc, ret) then
  55. esphttp.cleanup(httpc)
  56. return true, esphttp.status_code(httpc), response
  57. end
  58. if ret == esphttp.EVENT_ON_DATA then
  59. response = response .. data
  60. end
  61. end
  62. end
  63. else
  64. esphttp.cleanup(httpc)
  65. return false, responseCode, "perform httpClient error " .. err
  66. end
  67. end
  68. return httpLib