You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity向Java Spring Server发送请求时的编码乱码问题求助

解决UnityWebRequest向Spring Server发送请求时的编码乱码问题

问题说明

Unity中通过UnityWebRequest向Java Spring Server发送请求,当发送字符串house时,服务器端接收到的是houseÔÇï;但使用Postman等工具发送相同请求时无此问题。已尝试禁用UTF-8 BOM(new UTF8Encoding(false).GetBytes(jsonData))、切换至utf-32编码,均未解决问题。

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;
}

RegistrationRequest类定义

using System;

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

Spring Server的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

解决方案

1. 统一Content-Type头格式

将Content-Type与charset合并为一个请求头,避免Spring解析编码时出现歧义:

// 替换原有的两个头设置
webRequest.SetRequestHeader("Content-Type", "application/json; charset=utf-8");

Postman默认使用合并后的头格式,这是Unity与Postman请求的关键差异点。

2. 清理输入框中的隐藏字符

Trim()可能无法移除输入框中复制粘贴带来的零宽空格、非打印字符等,改用正则表达式严格清理:

using System.Text.RegularExpressions;

// 保留可见ASCII字符,移除其他特殊字符
req.email = Regex.Replace(usernameField.text.Trim(), @"[^\x20-\x7E]", "");
req.password = Regex.Replace(passwordField.text.Trim(), @"[^\x20-\x7E]", "");

3. 强制Spring端的请求编码

在Spring配置中添加强制UTF-8编码的过滤器,避免自动解析出错:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration
public class WebConfig {
    @Bean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        return filter;
    }
}

或者直接在application.yml中添加配置:

spring:
  http:
    encoding:
      force: true
      charset: UTF-8
      enabled: true

4. 验证JSON字节内容

在Unity端输出JSON的字节数组,对比Postman发送的请求字节,定位问题根源:

byte[] bytes = new UTF8Encoding(false).GetBytes(jsonData);
Debug.Log("JSON字节长度:" + bytes.Length);
foreach (byte b in bytes) {
    Debug.Log("字节:" + b.ToString("X2"));
}

内容的提问来源于stack exchange,提问作者Mergo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:00:20