Home >Backend Development >C++ >How to Send HTTP Requests (GET, POST, PUT, DELETE) in Unity using C#?
Use C# to send HTTP requests (GET, POST, PUT, DELETE) in Unity
Unity provides powerful features to simplify sending HTTP requests, including GET and POST requests. Here's a complete guide on how to handle these requests efficiently:
GET request:
Implementing GET requests using UnityWebRequest
is very simple:
<code class="language-csharp">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:
Sending form data requires an WWWForm
instance:
<code class="language-csharp">WWWForm form = new WWWForm(); form.AddField("param1", "value1"); UnityWebRequest uwr = UnityWebRequest.Post(url, form); yield return uwr.SendWebRequest();</code>
POST request containing JSON data:
For JSON based requests:
<code class="language-csharp">string json = JsonUtility.ToJson(dataObject); var uwr = new UnityWebRequest(url, "POST"); byte[] jsonToSend = System.Text.UTF8Encoding.UTF8.GetBytes(json); uwr.uploadHandler = new UploadHandlerRaw(jsonToSend); uwr.downloadHandler = new DownloadHandlerBuffer(); uwr.SetRequestHeader("Content-Type", "application/json"); yield return uwr.SendWebRequest();</code>
Multipart form data and files:
<code class="language-csharp">List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("name=John&age=30")); formData.Add(new MultipartFormFileSection("myFile", "myfile.txt")); UnityWebRequest uwr = UnityWebRequest.Post(url, formData); yield return uwr.SendWebRequest();</code>
HTTP methods other than GET and POST:
PUT:
<code class="language-csharp"> byte[] dataToPut = System.Text.Encoding.UTF8.GetBytes("数据"); UnityWebRequest uwr = UnityWebRequest.Put(url, dataToPut); yield return uwr.SendWebRequest();</code>
DELETE:
<code class="language-csharp"> UnityWebRequest uwr = UnityWebRequest.Delete(url); yield return uwr.SendWebRequest();</code>
The above is the detailed content of How to Send HTTP Requests (GET, POST, PUT, DELETE) in Unity using C#?. For more information, please follow other related articles on the PHP Chinese website!