Browse Source

Add C++ Http Request demo sample.

cosmy 9 years ago
parent
commit
bdb5035eb4

+ 33 - 0
Source/Samples/43_HttpRequestDemo/CMakeLists.txt

@@ -0,0 +1,33 @@
+#
+# Copyright (c) 2008-2016 the Urho3D project.
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+
+# Define target name
+set (TARGET_NAME 43_HttpRequestDemo)
+
+# Define source files
+define_source_files (EXTRA_H_FILES ${COMMON_SAMPLE_H_FILES})
+
+# Setup target with resource copying
+setup_main_executable ()
+
+# Setup test cases
+setup_test ()

+ 120 - 0
Source/Samples/43_HttpRequestDemo/HttpRequestDemo.cpp

@@ -0,0 +1,120 @@
+//
+// Copyright (c) 2008-2016 the Urho3D project.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#include <Urho3D/Core/CoreEvents.h>
+#include <Urho3D/Core/ProcessUtils.h>
+#include <Urho3D/Input/Input.h>
+#include <Urho3D/Network/HttpRequest.h>
+#include <Urho3D/UI/Font.h>
+#include <Urho3D/UI/Text.h>
+#include <Urho3D/UI/UI.h>
+
+#include "HttpRequestDemo.h"
+
+#include <Urho3D/DebugNew.h>
+
+URHO3D_DEFINE_APPLICATION_MAIN(HttpRequestDemo)
+
+HttpRequestDemo::HttpRequestDemo(Context* context) :
+    Sample(context)
+{
+}
+
+void HttpRequestDemo::Start()
+{
+    // Execute base class startup
+    Sample::Start();
+
+    // Create the user interface
+    CreateUI();
+
+    // Subscribe to basic events such as update
+    SubscribeToEvents();
+
+    // Set the mouse mode to use in the sample
+    Sample::InitMouseMode(MM_FREE);
+}
+
+void HttpRequestDemo::CreateUI()
+{
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+
+    // Construct new Text object
+    text_ = new Text(context_);
+
+    // Set font and text color
+    text_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
+    text_->SetColor(Color(1.0f, 1.0f, 0.0f));
+
+    // Align Text center-screen
+    text_->SetHorizontalAlignment(HA_CENTER);
+    text_->SetVerticalAlignment(VA_CENTER);
+
+    // Add Text instance to the UI root element
+    GetSubsystem<UI>()->GetRoot()->AddChild(text_);
+}
+
+void HttpRequestDemo::SubscribeToEvents()
+{
+    // Subscribe HandleUpdate() function for processing HTTP request
+    SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HttpRequestDemo, HandleUpdate));
+}
+
+void HttpRequestDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
+{
+    if (httpRequest_.Null())
+        httpRequest_ = new HttpRequest("http://httpbin.org/ip", "GET", {}, "");
+    else
+    {
+        // Initializing HTTP request
+        if (httpRequest_->GetState() == HTTP_INITIALIZING)
+            return;
+        // An error has occured
+        else if (httpRequest_->GetState() == HTTP_ERROR)
+        {
+            text_->SetText("An error has occured.");
+            UnsubscribeFromEvent("Update");
+        }
+        // Get message data
+        else
+        {
+            if (httpRequest_->GetAvailableSize() > 0)
+                message_ += httpRequest_->ReadLine();
+            else
+            {
+                text_->SetText("Processing...");
+
+                SharedPtr<JSONFile> json(new JSONFile(context_));
+                json->FromString(message_);
+
+                JSONValue val = json->GetRoot().Get("origin");
+
+                if (val.IsNull())
+                    text_->SetText("Invalid string.");
+                else
+                    text_->SetText("Your IP is: " + val.GetString());
+
+                UnsubscribeFromEvent("Update");
+            }
+        }
+    }
+}

+ 62 - 0
Source/Samples/43_HttpRequestDemo/HttpRequestDemo.h

@@ -0,0 +1,62 @@
+//
+// Copyright (c) 2008-2016 the Urho3D project.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#pragma once
+
+#include "Sample.h"
+
+/// Http request example.
+/// This example demonstrates:
+///     - How to use Http request API
+class HttpRequestDemo : public Sample
+{
+    URHO3D_OBJECT(HttpRequestDemo, Sample);
+
+public:
+    /// Construct.
+    HttpRequestDemo(Context* context);
+
+    /// Setup after engine initialization and before running the main loop.
+    virtual void Start();
+
+protected:
+    /// Return XML patch instructions for screen joystick layout for a specific sample app, if any.
+    virtual String GetScreenJoystickPatchString() const { return
+        "<patch>"
+        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">"
+        "        <attribute name=\"Is Visible\" value=\"false\" />"
+        "    </add>"
+        "</patch>";
+    }
+
+private:
+    /// Create the user interface.
+    void CreateUI();
+    /// Subscribe to application-wide logic update events.
+    void SubscribeToEvents();
+    /// Handle the logic update event.
+    void HandleUpdate(StringHash eventType, VariantMap& eventData);
+    
+    String message_;
+    SharedPtr<Text> text_;
+    SharedPtr<HttpRequest> httpRequest_;
+};