Sending HTTP requests in C # using Unity

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

What I want is:

  • send JSON data in the post request (I use the Unity serializer, so there is no need for a new one, I just want to pass a string in the post data and be able to set ContentType for application / json);
  • get the response code and body without problems;
  • do it all asynchronously without blocking the rendering of the user interface.

What I tried:

  • implementation with HttpWebRequest / HttpWebResponse, but it is too complicated and at a low level (if I do not find anything better, I will have to use it);
  • using WWW unity, but this does not meet my requirements;
  • using some external packages from NuGet - Unity does not accept them :(

Most of the problems were with multithreading, I'm not experienced enough in this in C #. The IDE I use is Intellij Rider.

+24
source share
2 answers

WWW API should do this, but UnityWebRequest replaced it, so I will respond to the new API. It is really easy. You must use a coroutine to do this with the Unity API, otherwise you will have to use one of the standard C # API web requests and Thread. With a coroutine, you can provide a request until it is done. This will not block the main thread or prevent other scripts from running.

Note :

In the examples below, if you are using anything below Unity 2017.2, replace SendWebRequest() with Send() and then replace isNetworkError with isError . This will then work for a lower version of Unity. Also, if you need to access the downloaded data in binary form, replace uwr.downloadHandler.text with uwr.downloadHandler.data . Finally, the SetRequestHeader function SetRequestHeader used to set the request header.

GET REQUEST :

 void Start() { StartCoroutine(getRequest("http:///www.yoururl.com")); } IEnumerator GetRequest(string uri) { UnityWebRequest uwr = UnityWebRequest.Get(uri); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); } else { Debug.Log("Received: " + uwr.downloadHandler.text); } } 

POST request with the form :

 void Start() { StartCoroutine(postRequest("http:///www.yoururl.com")); } 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("Error While Sending: " + uwr.error); } else { Debug.Log("Received: " + uwr.downloadHandler.text); } } 

POST request with Json :

  void Start() { StartCoroutine(postRequest("http:///www.yoururl.com", "your json")); } 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"); //Send the request then wait here until it returns yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); } else { Debug.Log("Received: " + uwr.downloadHandler.text); } } 

POST request with Multipart FormData / Multipart Form File :

 void Start() { StartCoroutine(postRequest("http:///www.yoururl.com")); } IEnumerator PostRequest(string url) { List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("field1=foo&field2=bar")); formData.Add(new MultipartFormFileSection("my file data", "myfile.txt")); UnityWebRequest uwr = UnityWebRequest.Post(url, formData); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); } else { Debug.Log("Received: " + uwr.downloadHandler.text); } } 

PUT request :

 void Start() { StartCoroutine(putRequest("http:///www.yoururl.com")); } IEnumerator PutRequest(string url) { byte[] dataToPut = System.Text.Encoding.UTF8.GetBytes("Hello, This is a test"); UnityWebRequest uwr = UnityWebRequest.Put(url, dataToPut); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); } else { Debug.Log("Received: " + uwr.downloadHandler.text); } } 

DELETE query :

 void Start() { StartCoroutine(deleteRequest("http:///www.yoururl.com")); } IEnumerator DeleteRequest(string url) { UnityWebRequest uwr = UnityWebRequest.Delete(url); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); } else { Debug.Log("Deleted"); } } 
+60
source

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; } 

The payload is an object that will be serialized for json. If all requests come to the same baseUrl, you can configure HttpClient globally and reuse it here.

+1
source

Source: https://habr.com/ru/post/1266503/


All Articles