I'm working on a WebGL application made with Unity, that will be integrated with a external hardware.
The communication between them is being made by APIs, sent by a third part company (responsible for the hardware). They demanded everything to be sent by POST with an empty JSON as body "{}". The problem was that UnityWebRequest.Post doesn't format the JSON file properly.
The project was working perfectly with my local tests (accessing local JSON files), but when they sent the final API host address I had to work around to change the UnityWebRequest.Post to .Put, since the Post method doesn't format the JSON correctly. After some code changes, it is working on the Editor perfectly. The problem is when it comes to the Browser.
Bellow you can see what I've tried so far:
IEnumerator GetJsonContent(string url)
{
var request = UnityWebRequest.Put(url, "{}");
request.method = "POST";
byte[] bodyRaw = Encoding.UTF8.GetBytes("{}");
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
while (!request.isDone)
{
yield return new WaitForEndOfFrame();
}
if (request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
var jsonContent = request.downloadHandler.text;
if (JsonCallback != null)
{
JsonCallback(jsonContent);
JsonCallback = null;
}
}
yield break;
}
In addition to that code, I've also tried:
var request = new UnityWebRequest(url, "POST");
Instead of the first two lines of the Coroutine.
The browser keeps throwing a 405 error, but the Postman returns values, but when I try to reproduce what I have on the browser on Postman, it says no "Body" is being sent. The feedback we received from the company responsible for the APIs was that we might be having problems with the CORS.
The weirdest part is that it works perfectly fine on Editor (with the same API address).
Thanks in advance.
The problem was solved.
It was related to the CORS (Cross-Origin Resource Sharing). For some reason our server was not set to communicate with their server, so we had to change settings in our server. The code above works perfectly! :-)