0

I am trying to send a PUT request using UnityWebRequest to update game data on a server. However, I keep getting the error:

css Copy Edit Error: 400 - {"message":"Invalid json data"} I have tested the same JSON in Postman, and it works correctly. But when sending it from Unity, the request fails with a 400 Bad Request error.

API's request sample

'{
    "gameId": "93bdd165-51aa-4aab-87c2-516a234465b9",
    "used": {
        "startBoosts": [
            {
                "name": "Head start",
                "quantity": 8
            },
            {
                "name": "Score multiplier",
                "quantity": 4
            }
        ],
        "normalBoosts": [
            {
                "name": "Magnet",
                "quantity": 8
            },
            {
                "name": "Force Shield",
                "quantity": 6
            },
            {
                "name": "Hyperdrive",
                "quantity": 1
            }
        ]
    },
    "collected": [
        {
            "name": "Magnet",
            "quantity": 1
        },
        {
            "name": "Force Shield",
            "quantity": 0
        },
        {
            "name": "Hyperdrive",
            "quantity": 3
        }
    ],
    "finalScore": 36598521
}'

json (string) generated in unity before uploading within the PUT method request

Generated JSON: {
  "gameId": "8eb97e75-8127-47e9-abd5-895e094b4e32",
  "used": {
    "startBoosts": [
      {
        "name": "Head start",
        "quantity": 0
      },
      {
        "name": "Score multiplier",
        "quantity": 0
      }
    ],
    "normalBoosts": [
      {
        "name": "Magnet",
        "quantity": 0
      },
      {
        "name": "Force Shield",
        "quantity": 0
      },
      {
        "name": "Hyperdrive",
        "quantity": 0
      }
    ]
  },
  "collected": [
    {
      "name": "Magnet",
      "quantity": 0
    },
    {
      "name": "Force Shield",
      "quantity": 0
    },
    {
      "name": "Hyperdrive",
      "quantity": 0
    }
  ],
  "finalScore": 0
}

Code:

private IEnumerator SendDeclareGameEndRequest()
{
    // Ensure BoostsManager is set
    BoostsManager boostsManager = FindObjectOfType<BoostsManager>();

    if (boostsManager == null)
    {
        Debug.LogError("BoostsManager not found!");
        yield break;
    }

    // Get game data
    GameEndData gameEndData = boostsManager.GetGameEndData(gameId, score.score);

    // Convert to JSON using Newtonsoft.Json
    string json = JsonConvert.SerializeObject(gameEndData, Formatting.Indented);

    Debug.Log("Generated JSON: " + json); // Debugging output

    byte[] jsonToSend = System.Text.Encoding.UTF8.GetBytes(json);

    using (UnityWebRequest request = new UnityWebRequest(apiUrl, "PUT"))
    {
        request.uploadHandler = new UploadHandlerRaw(jsonToSend);
        request.downloadHandler = new DownloadHandlerBuffer();

        request.SetRequestHeader("session-token", sessionToken);
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("Game End Declared Successfully: " + request.downloadHandler.text);
        }
        else
        {
            Debug.LogError("Error: " + request.responseCode + " - " + request.downloadHandler.text);
        }
    }
}

Debugging Steps Taken

  • Checked the generated JSON in Unity logs and verified it matches Postman.
  • Ensured Content-Type is correctly set to application/json.
  • Tried sending data as a string instead of a byte[], but UnityWebRequest requires byte[] for PUT.
  • Used both Unity’s built-in JsonUtility and Newtonsoft.Json for serialization.
3
  • Are you sure thats right? Have you tried setting put and putting the data in the Put request, also might need to include your upload handler, cos, it could be wrong ... Commented Feb 11 at 20:07
  • Have you tried a normal UnityWebRequest.Put? Basically it should in theory do the same thing anyway .. already uses a UploadHandlerRaw, if given a string uses UTF8 encoding .. the only thing different is it still uses a content type header application / octet stream .. maybe that's essential Commented Feb 11 at 21:20
  • On the other hand the most probable guess would rather be the session token isn't valid ... Commented Feb 12 at 8:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.