Using C# to make HTTP requests in Unity
When developing games or interactive applications in Unity, the ability to send HTTP requests is critical for tasks such as user authentication, getting data from web services, and submitting game events. This article demonstrates how to send HTTP GET and POST requests using C# in Unity to meet the requirements specified in the question.
UnityWebRequest: Request and response handling
UnityWebRequest provides a convenient and efficient way to make web requests in Unity. It handles coroutines and multi-threading internally, makes asynchronous requests and prevents UI freezing.
GET request
To send a GET request, just call UnityWebRequest.Get() and pass in the URI. The response text can be accessed via uwr.downloadHandler.text.
<code class="language-csharp">IEnumerator getRequest(string uri) { UnityWebRequest uwr = UnityWebRequest.Get(uri); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) Debug.Log("发送错误: " + uwr.error); else Debug.Log("接收: " + uwr.downloadHandler.text); }</code>
POST request containing form data
To send a POST request containing form data, build the form using WWWForm and pass it to UnityWebRequest.Post().
<code class="language-csharp">IEnumerator postRequest(string url) { WWWForm form = new WWWForm(); form.AddField("myField", "myData"); form.AddField("Game Name", "Mario Kart"); UnityWebRequest uwr = UnityWebRequest.Post(url, form); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) Debug.Log("发送错误: " + uwr.error); else Debug.Log("接收: " + uwr.downloadHandler.text); }</code>
JSON POST request
For JSON POST requests, create a raw upload handler and manually set the Content-Type header to application/json.
<code class="language-csharp">IEnumerator postRequest(string url, string json) { var uwr = new UnityWebRequest(url, "POST"); byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json); uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend); uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); uwr.SetRequestHeader("Content-Type", "application/json"); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) Debug.Log("发送错误: " + uwr.error); else Debug.Log("接收: " + uwr.downloadHandler.text); }</code>
PUT, DELETE and Multipart/Form-Data
UnityWebRequest also supports PUT, DELETE and multipart/form-data requests. See the provided code snippet for a detailed example.
By following these code examples, you can quickly send and handle HTTP requests in your Unity game or application, giving you powerful tools for seamless data exchange.
The above is the detailed content of How to Make HTTP GET and POST Requests in Unity using C#?. For more information, please follow other related articles on the PHP Chinese website!