43_HttpRequestDemo.as 2.5 KB

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