springunity-game-engineencodingutf-8unitywebrequest

How to fix my encoding Issues between Unity and Java Spring Server?


I am sending a UnityWebRequest to my Java Spring Server from my application in Unity. If I send the word "house", then "houseÔÇï" arrives there. However, the error does not happen when I send the request from Postman, for example.

The creation of the Request in Unity:

    private UnityWebRequest CreateRegistrationRequest()
    {
        var webRequest = UnityWebRequest.Post(REGISTRATION_URL, string.Empty);

        webRequest.SetRequestHeader("Content-Type", "application/json");
        webRequest.SetRequestHeader("charset", "utf-8");

        var req = new RegistrationRequest();

        req.email = usernameField.text.Trim();
        req.password = passwordField.text.Trim();

        string jsonData = JsonUtility.ToJson(req);
        webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(jsonData));
        return webRequest;
    }

My application.yml:

server:
  error:
    include-message: always
    include-binding-errors: always
spring:
  datasource:
    password: password
    url: jdbc:postgresql://localhost:5432/registration?charSet=UTF8
    username:
  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: true
        connection:
          charSet: UTF-8
    show-sql: true

RegistrationRequest:

using System;

[Serializable]
public class RegistrationRequest
{
    public string email;
    public string password;
}

As mentioned, the error does not appear when I send the request from Postman.

I assume that the issue has something to do with the Byte Order Mark (BOM), which seems to be optional in UFT-8 and is not supported by every platform. Therefore I tried to disable the BOM:

        webRequest.uploadHandler = new UploadHandlerRaw(new UTF8Encoding(false).GetBytes(jsonData));

It did not work. Same issue. I even tried to change the encoding to utf-32, but same issue as well.


Solution

  • Knowing now that actually the two usernameField and passworsField are TextMeshProUGUI:

    This is quite a known "issue"!

    The TextMeshProUGUI component of a TMP_InputField should NOT be used to retrieve the text value!

    Indeed it might even be completely unusable since e.g. for a password type field the text component itself literally only contains "*******". It is also known (as in your case) to contain some hidden control characters only meaningful to the TMP_InputField component itself.

    See e.g. this thread

    ⇒ What you want to do instead is make both fields of type TMP_InputField instead.

    This one also has a property called text which will contain the actual value without hidden control characters!