Hello everyone.

The Mixed Reality Forums here are no longer being used or maintained.

There are a few other places we would like to direct you to for support, both from Microsoft and from the community.

The first way we want to connect with you is our mixed reality developer program, which you can sign up for at https://aka.ms/IWantMR.

For technical questions, please use Stack Overflow, and tag your questions using either hololens or windows-mixed-reality.

If you want to join in discussions, please do so in the HoloDevelopers Slack, which you can join by going to https://aka.ms/holodevelopers, or in our Microsoft Tech Communities forums at https://techcommunity.microsoft.com/t5/mixed-reality/ct-p/MicrosoftMixedReality.

And always feel free to hit us up on Twitter @MxdRealityDev.

How to integrate Rest api Get and Post Call Unity c#?

Hello All,

How to integrate Rest web api get and post call in game object. ?

Best Answer

  • SpheredCazualSpheredCazual ✭✭
    Answer ✓

    These would be your post fields you are sending:

    form.AddField("myField", "myData");
    

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

Answers

  • have a look at unity's manual : https://docs.unity3d.com/Manual/UnityWebRequest.html you can use it to use get and post requests

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

  • @SpheredCazual
    Thanks for quick response. i go through on Unitywebrequest.html but when call post method i get this error.

    at** WinRTBridge.Utils.ThrowNewNullReferenceException(String message)**
    at UnityEngineProxy.InternalCalls.PInvokeCalls.MonoBehaviour_CUSTOM_StartCoroutine_Auto(IntPtr param_0, Int64 param_1)
    at UnityEngineProxy.InternalCalls.MonoBehaviour_CUSTOM_StartCoroutine_Auto(Object self, Object routine)
    at UnityEngine.MonoBehaviour.StartCoroutine(IEnumerator routine)
    at NewBehaviourScriptAPI.NewBehaviourScript.POST(String url, Dictionary2 post, Dictionary2 Headers, Action`1 Callback)
    at NewBehaviourScript1.OnSelect()
    at UnityEngine.Events.InvokableCall.Invoke(Object[] args)
    at UnityEngine.Events.InvokableCallList.Invoke(Object[] parameters)
    at UnityEngine.Events.UnityEvent.Invoke()
    at OnSelectEvent.OnSelect()
    at OnSelectEvent.$Invoke0OnSelect(Int64 instance, Int64* args)
    at UnityEngine.Internal.$MethodUtility.InvokeMethod(Int64 instance, Int64* args, IntPtr method)

  • Please post your code so I can see where it may go wrong?

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

  • @SpheredCazual

    public void OnSelect() {
    NewBehaviourScript db = new NewBehaviourScript();
    Dictionary<string, string> data = new Dictionary<string, string>();
    data.Add("message", "light_on");
    Dictionary<string, string> Headers = new Dictionary<string, string>();
    Headers.Add("xtokenaccess","TOKEN");
    // Headers.Add("Content-Type", "application/json");
    var results = db.POST("SERVICE URl", data, Headers);
    }

    Hear Is db.POST method;

    private IEnumerator coroutine;

        public WWW POST(string url, Dictionary<string, string> post, Dictionary<string, string> Headers, System.Action<Object> Callback = null)
        {
            WWWForm form = new WWWForm();
            foreach (KeyValuePair<String, String> post_arg in post)
            {
                form.AddField(post_arg.Key, post_arg.Value);
            }
            byte[] rawData = form.data;
            Dictionary<string, string> headers = form.headers;            
            foreach (KeyValuePair<String, String> header_arg in Headers)
            {
                headers[header_arg.Key] = header_arg.Value;
            }
            WWW www = new WWW(url, rawData, headers);
            coroutine = WaitForRequest(www);
            StartCoroutine(coroutine);
            return www;
        }
    
        /// <summary>
        /// Waits for request.
        /// </summary>
        /// <param name="www">The WWW.</param>
        /// <param name="Callback">The callback.</param>
        /// <param name="isTexture">This is texture or not.</param>
        /// <returns>System.Collections.IEnumerator.</returns>
        private IEnumerator WaitForRequest(WWW www, System.Action<System.Object> Callback = null, bool isTexture = false)
        {
            yield return www;
            Object r;
            if (www.error == null)
            {
                //Ok
                if (!isTexture)
                    r = "{err:false,data:" + www.text + "}";
                else
                    r = www.texture;
    
                if (Callback != null)
                    Callback(r);
            }
            else
            {
                //send error
                r = "{err:\"" + www.error + "\",data:false}";
                if (Callback != null)
                    Callback(r);
            }
        }
    
  • SpheredCazualSpheredCazual ✭✭
    edited October 2016

    @Ankit09_Sangani, you are still using the old www system as per your line of code

    WWW www = new WWW(url, rawData, headers); 
    

    you should be using the new method: (UnityWebRequest.Post) as per the link to the documentation I provided up above, it should then work ;-)

    WWWForm form = new WWWForm();
        form.AddField("myField", "myData");
    
        UnityWebRequest www = UnityWebRequest.Post("http://www.my-server.com/myform", form);
        yield return www.Send();
    

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

  • edited October 2016

    @SpheredCazual

    Thank you so much SpheredCazual
    I am quite new in Unity and hololens. how can i pass header UnityWebRequest.post()

  • cwulecwule
    edited October 2016

    I would also be interested in that question, since I would like to retrieve and update the IPD via webrequest.

    I have two problems:

    • GET: I have integrated a unitywebrequest that works well to retrieve the IPD in the editor but fails in the HoloLens. In this request I send the authorization via
      UnityWebRequest www = UnityWebRequest.Get(ipdaddress); www.SetRequestHeader("AUTHORIZATION", authorization);

    • POST: Since I cannot send an "empty" POST request with no form and just the uri parameters in the request uri, I could not figure out how to use unitywebrequest. I wrote a httpwebrequest instead, which again works fine in the editor and updates the IPD. Here I send the credentials via
      NetworkCredential usercred = new NetworkCredential("admin", "password"); req.Credentials = usercred;

    If I run these requests in the HoloLens, there are debug messages:
    Error: could not find assembly System.Private.Networking.dll in which type System.Net.ICredentialsByHost resides. Error: could not find assembly System.Private.Networking.dll in which type System.Net.NetworkCredential resides. Error: could not find assembly System.Private.Networking.dll in which type System.Net.ICredentialsByHost resides Error: could not find assembly System.Private.Networking.dll in which type System.Security.SecureString resides.

  • @cwule
    In unity project settings make sure InternetClient ,InternetClientServer Capabilities were true.

  • SpheredCazualSpheredCazual ✭✭
    Answer ✓

    These would be your post fields you are sending:

    form.AddField("myField", "myData");
    

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

  • cwulecwule
    edited October 2016

    Thanks a lot for the tips!
    @Ankit09_Sangani I have these turned on. The error still appears. The WindowsDevicePortalWrapper might make things much easier but it seems like it doesn't work yet for unity because of the lacking support for .NET4.5.2.

    @SpheredCazual : I also found this in the docs and played around but haven't figured out how to provide the formdata, so that the post request is correct. Eg. if my uri should be
    http://127.0.0.1:10080/api/holographic/os/settings/ipd?ipd=60000
    what should I put in the form.AddField?

  • SpheredCazualSpheredCazual ✭✭
    edited October 2016

    form.AddField("ipd", "60000");

    and change the url to
    http://127.0.0.1:10080/api/holographic/os/settings/ipd

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

  • I noticed that all calls above are based on HTTP. If i look at the documentation of UnityWebRequest i noticed that they only talk about standard HTTP calls. Does UnityWebRequest supports SSL? And if not does WWW support it?

  • WWW, is not a good choice as it does not work on the hololens, I have been using the UnityWebRequest with SSL fine, but the above question was to a local address so there was no need for SSL ;-)

    creative mind, free thinker, dreamer, maker, mostly working on games and doodling around with gadgets, Sphered Cazual/Elite/Master of the Universe/Dad/Husband @mariovermeulen

  • I have been using WWW on a HoloLens without any problems. In my case i connect to an Azure Cloud Service. Does the HoloLens team acknowledge the fact that using UnityWebRequest is the way to go? The reason we started to use WWW again was that we had issues using UnityWebRequest in POST calls from HoloLens.

  • Hi @SpheredCazual

    What is the maximum length of a string in Unity, that can be populated from WWW.text?
    Currently i received only 4088 Char string as response but actual response it is more then 20000 Char string.So, i can't got proper Data... Please help me out ..

    thanks

  • Hello guys!
    Check my plugin for Unity, working with promises is better!
    https://github.com/proyecto26/RestClient (Supported all platforms)

    Also you can see the demo, it’s very easy!
    Let me know what you think, Nicholls

  • Hi guys,
    When I use UnityWebRequest, I am able to send HTTP Get Request successfully, but I am fail with HTTPS Get Request even though I checked all permissions for the publish settings.

    So my question is that how to send HTTPS request in Hololens? Please help me out

    Thanks!

  • HeikoooHeikooo
    edited July 2018

    @Ankit09_Sangani said:
    @SpheredCazual

    Thank you so much SpheredCazual
    I am quite new in Unity and hololens. how can i pass header UnityWebRequest.post()

    Hey guys,
    I read that the wwwForm.headers only contains one header, is there a walk around for 2 headers ( Content-Type : application/json and token : 12345) ? I want to use the post method.
    Thanks for your support =)

Sign In or Register to comment.