Unity web request acting stupid.

Ok, below is the code and the utterly stupid way it’s working.

I send a web request to an API on my server. It’s technically a non-existent php file and it’s handled by a WordPress plugin which responds with a JSON.

If the request.downloadHandler.text response looks like this:

{“status”:“ok”,“Login”:“Valid”,“ViewEula”:true,“SI”:“7036ac55b1a6aa62391cdf1b5ab567c9”}

Everything works as intended. However, if the request.downloadHandler.text looks like this:

{“status”:“error”,“error”:“Invalid username or password.”}

Web request detects that as a request.isHttpError and throws a 404 error:

HTTP/1.1 404 Not Found

I’m having to throw in another check when it detects that 404 to tell it, look if it really is a json response then it’s not a 404 error.

Here’s the code I should be able to use.

    public IEnumerator MyGetRequest(string url, WWWForm formData, Action<bool> callback)
    {
        using (UnityWebRequest request = UnityWebRequest.Post(url, formData))
        {
            // Send the request and wait for a response
            yield return request.SendWebRequest();
            Debug.Log(request.downloadHandler.text);
            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log(request.error);
                callback(false);
            }
            else
            {
                if (IsValidJson(request.downloadHandler.text))
                {
                    thischeck = FromJSON(request.downloadHandler.text);
                    callback(true);
                }
                else
                {
                    callback(false);
                }
            }
        }
    }

Instead, I’m having to double check to make sure the error it’s detecting really is an error:

    public IEnumerator MyGetRequest(string url, WWWForm formData, Action<bool> callback)
    {
        using (UnityWebRequest request = UnityWebRequest.Post(url, formData))
        {
            // Send the request and wait for a response
            yield return request.SendWebRequest();
            if (request.isNetworkError || request.isHttpError)
            {
                if (!IsValidJson(request.downloadHandler.text))
                {
                    callback(false);
                }
                else
                {
                    thischeck = FromJSON(request.downloadHandler.text);
                    callback(true);
                }
            }
            else
            {
                if (IsValidJson(request.downloadHandler.text))
                {
                    thischeck = FromJSON(request.downloadHandler.text);
                    callback(true);
                }
                else
                {
                    callback(false);
                }
            }
        }
    }

Always get network stuff working outside of Unity in either curl or PostMan, then connect a proxy such as Charles and start trying to replicate the traffic shape with UnityWebRequest.

Any other way risks wasting a lot of your time for trivial issues that only the above way will instantly reveal.

2 Likes
Unable to send PUT request via UnityWebRequest
How Can i Connect Unity to Postgres Database
Google Maps Integration for Real World Race Track
UnityWebRequest error connection API
Dll import error
libcurl issue
UnityWebRequest and image upload
WebRequest Proxy Authentification
A problem with WWW Form and PhP
SendWebRequest.Post() doesn't send variables
An error
Why Spawning is not working?
How to create a web session for one-time basic authentication
Error on http request
UnityWebRequest - Unable to complete SSL connection
Unity WebRequest
User Image Upload
Problems with Unitywebrequest
webgl error on System.IO.StreamReader
How to use cURL in Unity
UnityWebRequest error Cannot connect to destination host
Can't send email to users
Calling method not working...
Working with excel spreadsheets?
UnityWebRequest not working on Android API level 33
Unable to load texture from server in iOS
Network Port - connecting Unity 3D with outside device
UnityWebRequest.Post not sending anything to my webserver.
Both UnityWebRequest and WWW are not able to download any file from LAN
Any sort of JSON deserializing stops code completely
Uploading File to Server from Android
ZeroMQ (ZMQ) deployed on Android?
Can no longer get response from HttpWebRequest when 400 returned at Unity 2020,2021
Simple Mobile database connection
C# to PHP - WWW Update?
UnityWebRequestException:Unknown Error  WebGL
Trying to get float to MySQL, it gets rounded.
Message from Nodejs websocket to Unity
AWS / Cognito - difficulties with login
UnityWebRequest.Post dosen't work
HttpClient - Timeout - Different behavior between VS and Unity
RSA server - client simulation exchange keys
UnityWebRequest to Local Network Shared Folder
POST request doesn't work (UnityWebRequest)
How to change the value of ToggleGroup to a string? And how to pass Togglegroup values to WWWFrom?
Troubleshooting PHP Login Script
GPT Api Integration
convert webRequest.downloadHandler.text to an array
Steps to send and recv image
Can post data using toggle question to Google form?
Unity Texture 2D from Uint64List byte[]
yield return web.SendWebRequest() crashes on Samsung Galaxy Tab A7 Lite
Communication between app and service
is a non-blocking HttpWebRequest possible?
Unity Player authentication and Request with JSON
Network debugger like in googleChrome devtool for HTTP requests debugging
How can I remove an array item?
Assetbundle DownloadHandlerFile
IM back DECODING networking IMAGE BYTES
Assistance with JSON response
Can't retrieve DownloadHandler.text from a UnityWebRequest.Put that has failed
mqtt Certificate fails.
Send email using PHP
UnityWebRequest shows an "?" when downloading an image from a server
Which premissions do I need for MySQL connection in Android
issue with nonascii filename when using synology nas api.
Can I send information to a browser from a Unity app built for Windows?
Post request accessing the image.
Azure OCR on local image
Unity and ZeroMQ?
Android file upload working in Simulator but not phone¿¿¿¿
Uploading Images Android
An issue with Open AI API and nullable float variable(float?)
TCP Connection Refused
UnityWebRequestTexture.GetTexture() web request is silently failing
Use Get instead Post
using stable diffusion
Dataverse Web API authentication
Coroutine to make a unitywebrequest won't execute
Trying to get elevenlabs TTS API working
Suggested way of receiving audio data through TCP conection and update audio clip in Unity
[Solved] Best Way to Upload and Store CSV Data from a Unity WebGL Game
Getting time from a server؟؟؟
Post to php issue!
The problem is in getting the time from the server
Recieving video continuous grey image
how to use UnityWebRequest on visual scripting ?
How can I debug WebSockets requests?
Float Array To AudioClip
HttpClient Fails to Get Access
Package manager 401 error with custom scoped registry
Can Unity WebGL use the Amazon AWS Signing V4 without SDK? Like js?

There is no stupid behavior here. isNetworkError tells you that cvomminication with the server has failed, while isHttpError means the server responded with HTTP code that means error (4xx or 5xx).
When you get a network error, the download handler will have no or only partial data, so you can pretty much not validate JSON there.
When you get HTTP error, the download handler contains a server sent message detailing what was the error.

From the example you gave, the server actually sends you a questionable response in the case where you get an error. The 404 generally should be returned when requested thing is not found, there is a different error code for authorization issues, usually 403, see: List of HTTP status codes - Wikipedia

1 Like