Sending http requests in C# with Unity

前端 未结 2 1767
暖寄归人
暖寄归人 2020-11-22 12:33

How can I send HTTP GET and POST requests in C# with Unity?

What I want is:

  • send json data in post request (I use Unity serializer, so no need in new o
2条回答
  •  有刺的猬
    2020-11-22 12:40

    Use HttpClient and something like:

    public static HttpContent DoPost(object payload, string subPath)
        {
            var httpClient = new HttpClient();
    
            HttpClient.BaseAddress = new Uri(Global.BaseUrl);
            HttpClient.DefaultRequestHeaders.Clear();
            HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // if you're using json service
    
            // make request
            var response = Global.HttpClient.PostAsJsonAsync(subPath.TrimLeadingSlash(), payload).Result;
    
            // check for error
            response.EnsureSuccessStatusCode();
    
            // return result
            return response.Content;
        }
    

    Payload is an object to be serialized to json. If all requests are going to the same baseUrl, you can set up HttpClient globally, and reuse it here

提交回复
热议问题