43_HttpRequestDemo.lua 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. -- Http request example.
  2. -- This example demonstrates:
  3. -- - How to use Http request API
  4. require "LuaScripts/Utilities/Sample"
  5. local message = ""
  6. local text = nil
  7. local httpRequest = nil
  8. function Start()
  9. -- Execute the common startup for samples
  10. SampleStart()
  11. -- Create the user interface
  12. CreateUI()
  13. -- Set the mouse mode to use in the sample
  14. SampleInitMouseMode(MM_FREE)
  15. -- Subscribe to basic events such as update
  16. SubscribeToEvents()
  17. end
  18. function CreateUI()
  19. -- Construct new Text object
  20. text = Text:new()
  21. -- Set font and text color
  22. text:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  23. text.color = Color(1.0, 1.0, 0.0)
  24. -- Align Text center-screen
  25. text.horizontalAlignment = HA_CENTER
  26. text.verticalAlignment = VA_CENTER
  27. -- Add Text instance to the UI root element
  28. ui.root:AddChild(text)
  29. end
  30. function SubscribeToEvents()
  31. -- Subscribe HandleUpdate() function for processing HTTP request
  32. SubscribeToEvent("Update", "HandleUpdate")
  33. end
  34. function HandleUpdate(eventType, eventData)
  35. -- Create HTTP request
  36. if httpRequest == nil then
  37. httpRequest = network:MakeHttpRequest("http://httpbin.org/ip")
  38. else
  39. -- Initializing HTTP request
  40. if httpRequest.state == HTTP_INITIALIZING then
  41. return
  42. -- An error has occurred
  43. elseif httpRequest.state == HTTP_ERROR then
  44. text.text = "An error has occurred."
  45. UnsubscribeFromEvent("Update")
  46. -- Get message data
  47. else
  48. if httpRequest.availableSize > 0 then
  49. message = message .. httpRequest:ReadLine()
  50. else
  51. text.text = "Processing..."
  52. local json = JSONFile:new()
  53. json:FromString(message)
  54. local val = json:GetRoot():Get("origin")
  55. if val.isNull then
  56. text.text = "Invalid string."
  57. else
  58. text.text = "Your IP is: " .. val:GetString()
  59. end
  60. json:delete()
  61. httpRequest:delete()
  62. UnsubscribeFromEvent("Update")
  63. end
  64. end
  65. end
  66. end
  67. -- Create XML patch instructions for screen joystick layout specific to this sample app
  68. function GetScreenJoystickPatchString()
  69. return
  70. "<patch>" ..
  71. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
  72. " <attribute name=\"Is Visible\" value=\"false\" />" ..
  73. " </add>" ..
  74. "</patch>"
  75. end