Http.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. --HTTP API
  2. --Localized Lua Library
  3. --Localized LIKO-12 Peripherals
  4. local web = WEB
  5. --The API
  6. local http = {}
  7. function http.request(url, postData, headers, method)
  8. if not web then return false, "HTTP API Requires WEB Peripheral" end
  9. --The request arguments.
  10. local args = {}
  11. --The request header.
  12. args.headers = headers
  13. --POST method
  14. if postData then
  15. args.method = "POST"
  16. args.data = tostring(postData)
  17. end
  18. --Set method
  19. args.method = method or args.method
  20. --Send the web request
  21. local ticket = WEB.send(url,args)
  22. --Wait for it to arrived
  23. for event, id, url, data, errnum, errmsg, errline in pullEvent do
  24. --Here it is !
  25. if event == "webrequest" then
  26. --Yes, this is the correct package !
  27. if id == ticket then
  28. if data then
  29. data.code = tonumber(data.code)
  30. if data.code < 200 or data.code >= 300 then --Too bad...
  31. cprint("HTTP Failed Request Body: "..tostring(data.body))
  32. return false, "HTTP Error: "..data.code, data
  33. end
  34. return data.body, data --Yay
  35. else --Oh, no, it failed
  36. return false, errmsg
  37. end
  38. end
  39. elseif event == "keypressed" then
  40. if id == "escape" then
  41. return false, "Request Canceled" --Well, the user changed his mind
  42. end
  43. end
  44. end
  45. end
  46. function http.get(url, headers)
  47. if not web then return false, "HTTP API Requires WEB Peripheral" end
  48. return http.request(url, false, headers)
  49. end
  50. function http.post(url, postData, headers)
  51. if not web then return false, "HTTP API Requires WEB Peripheral" end
  52. return http.request(url, postData, headers)
  53. end
  54. function http.urlEscape(str)
  55. if not web then return url end
  56. return web.urlEncode(str)
  57. end
  58. function http.urlEncode(data)
  59. local encode = {}
  60. for k,v in pairs(data) do
  61. encode[#encode + 1] = k.."="..v
  62. end
  63. return table.concat(encode,"&")
  64. end
  65. return http