Home > Software design >  How does Unity receive http request?
How does Unity receive http request?

Time:01-12

I want to accept http request to order prefab move, so how to receive http request in unity 3D?

CodePudding user response:

If you mean you want to build a web service in your Unity app.

RESTful-Unity is an easy-to-use plugin.

  1. Define the api routing
RoutingManager routingManager = new RoutingManager();
routingManager.AddRoute(new Route(Route.Type.POST, "/path/to/call", "PrefabInvoke.Move"));
  1. Create an Invoke to response the request
namespace RESTfulHTTPServer.src.invoker
{
    public class PrefabInvoke : MonoBehaviour
    {
        public static Response Move(Request request)
        {
            Response response = new Response();
            string responseData = "";
            string json = request.GetPOSTData();
            bool valid = true;

            UnityInvoker.ExecuteOnMainThread.Enqueue (() => {

                    Debug.Log(json);
                    try
                    {
                       //TODO: Parse Json string and do somthing

                        response.SetHTTPStatusCode((int)HttpStatusCode.OK);
                        responseData = "sucess message";
                    }
                    catch (Exception ex)
                    {
                        valid = false;
                        string msg = "failed to deseiralised JSON";
                        responseData = msg;
                    }
                    
            });

            // Wait for the main thread
            while (responseData.Equals("")) {}

            // Filling up the response with data
            if (valid) {

                // 200 - OK
                response.SetContent(responseData);
                response.SetHTTPStatusCode ((int)HttpStatusCode.OK);
                response.SetMimeType (Response.MIME_CONTENT_TYPE_JSON);
            } else {

                // 406 - Not acceptable
                response.SetContent("Somthing wrong");
                response.SetHTTPStatusCode((int) HttpStatusCode.NotAcceptable);
                response.SetMimeType(Response.MIME_CONTENT_TYPE_HTML);
            }

            return response;
        }
    }
}

  •  Tags:  
  • Related