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 one, I just want to pass string in post data and have ability to set ContentType to application/json);
- get response code and body without any problems;
- do it all asynchronous without blocking ui rendering.
What I've tried:
- implementing with HttpWebRequest/HttpWebResponse, but it's too hard and low level (if I won't found anything better, I'll have to use it);
- using unity WWW, but it doesn't match my requirements;
- using some external packages from NuGet - Unity don't accept them :(
Most problems were with threading, I'm not experienced enough in it in C#. Text editor, I use, is Intellij Rider.
Use HttpClient and something like:
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
The
WWW
API should get this done butUnityWebRequest
replaced it so I will answer the newer API. It's really simple. You have to use coroutine to do this with Unity's API otherwise you have have to use one of C# standard web request API and Thread. With coroutine you can yield the request until it is done. This will not block the main Thread or prevent other scripts from running.Note:
For the examples below, if you are using anything below Unity 2017.2, replace
SendWebRequest()
withSend()
and then replaceisNetworkError
withisError
. This will then work for the lower version of Unity. Also, if you need to access the downloaded data in a binary form instead, replaceuwr.downloadHandler.text
withuwr.downloadHandler.data
. Finally, theSetRequestHeader
function is used to set the header of the request.GET request:
POST request with Form:
POST request with Json:
POST request with Multipart FormData/Multipart Form File:
PUT request:
DELETE request: