util_http.lua 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. local util_http = {}
  2. -- 用于生成 http 请求的 id
  3. local http_count = 0
  4. -- 记录正在运行的 http 请求数量
  5. local http_running_count = 0
  6. local luat_http_code_desc = {
  7. [0] = "HTTP_OK",
  8. [-1] = "HTTP_ERROR_STATE",
  9. [-2] = "HTTP_ERROR_HEADER",
  10. [-3] = "HTTP_ERROR_BODY",
  11. [-4] = "HTTP_ERROR_CONNECT",
  12. [-5] = "HTTP_ERROR_CLOSE",
  13. [-6] = "HTTP_ERROR_RX",
  14. [-7] = "HTTP_ERROR_DOWNLOAD",
  15. [-8] = "HTTP_ERROR_TIMEOUT",
  16. [-9] = "HTTP_ERROR_FOTA",
  17. }
  18. --- 对 http.request 的封装
  19. -- @param timeout 超时时间(单位: 毫秒)
  20. -- @param method 请求方法
  21. -- @param url 请求地址
  22. -- @param headers 请求头
  23. -- @param body 请求体
  24. function util_http.fetch(timeout, method, url, headers, body)
  25. collectgarbage("collect")
  26. timeout = timeout or 1000 * 20
  27. local opts = { timeout = timeout }
  28. http_count = http_count + 1
  29. http_running_count = http_running_count + 1
  30. local id = "http_" .. http_count
  31. local res_code, res_headers, res_body = -99, {}, ""
  32. util_netled.blink(50, 50)
  33. log.debug("util_http.fetch", "开始请求", "id:", id)
  34. res_code, res_headers, res_body = http.request(method, url, headers, body, opts).wait()
  35. log.debug("util_http.fetch", "请求结束", "id:", id, "code:", res_code, "desc:", luat_http_code_desc[res_code])
  36. http_running_count = http_running_count - 1
  37. if http_running_count == 0 then
  38. util_netled.blink()
  39. end
  40. collectgarbage("collect")
  41. return res_code, res_headers, res_body
  42. end
  43. return util_http