Use .NET's own httpClient class on Unity

前端 未结 2 892
北海茫月
北海茫月 2020-12-21 10:18

I\'m trying to do a HTTP Delete request from Unity and bump into the idea of use the HttpRequest class included in the System.Web namespace of .Net

How can I achieve

相关标签:
2条回答
  • 2020-12-21 11:00

    In the current versions of Unity httpClient is supported out of the box even on .NET Standard 2.0 targets. Here is sample code on how I use it to access a REST api.

    public static async Task<Resource> GetResource()
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(URL);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await httpClient.GetAsync("api/session");
                if (response.StatusCode != HttpStatusCode.OK)
                    return null;
                var resourceJson = await response.Content.ReadAsStringAsync();
                return JsonUtility.FromJson<Resource>(resourceJson);
            }
        }
    

    Copy of my answer on https://forum.unity.com/threads/httpclient-on-net-standard-2-0.608800/

    0 讨论(0)
  • 2020-12-21 11:19

    HttpClient is only available in 4.5 NET and above and Unity does not use that version. Unity uses about 3.5 .NET version.

    If you are using Unity 5.3, UnityWebRequest.Delete can be used to make a Delete request. It can be found in the Experimental.Networking namespace. If you are using Unity 5.4 and above,UnityWebRequestcan be found in the UnityEngine.Networking; namespace.

    Full working example:

    IEnumerator makeRequest(string url)
    {
        UnityWebRequest delReq = UnityWebRequest.Delete(url);
        yield return delReq.Send();
    
        if (delReq.isError)
        {
            Debug.Log("Error: " + delReq.error);
        }
        else
        {
            Debug.Log("Received " + delReq.downloadHandler.text);
        }
    }
    

    Usage:

    StartCoroutine(makeRequest("http://www.example.com/whatever"));

    Make sure to include using UnityEngine.Networking. You can find complete examples with it here.


    EDIT (UPDATE)

    Unity now supports .NET 4.5 so you can now use HttpClient if you wish. See this post for how to enable it.

    After enabling it, Go to <UnityInstallationDirectory>\Editor\Data\MonoBleedingEdge\lib\mono\4.5 or for example, C:\Program Files\Unity\Editor\Data\MonoBleedingEdge\lib\mono\4.5 on my computer.

    Once in this directory, copy System.Net.Http.dll to your <ProjectName>\Assets directory and you should be able to use HttpClient after importing the System.Net.Http namespace. If there are some other error about missing dependencies, you can get the dlls from this path too and copy them to your <ProjectName>\Assets directory too.

    0 讨论(0)
提交回复
热议问题