Use .NET's own httpClient class on Unity

前端 未结 2 908
北海茫月
北海茫月 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 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(resourceJson);
            }
        }
    

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

提交回复
热议问题