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

SAP BTP Neo环境Servlet读取印度语言字段显示为问号求助

SAP BTP Neo Servlet读取HANA XS多语言字段显示问号问题

在SAP HANA XS中有一张表,部分字段包含多种印度语言的值。部署在SAP BTP Neo环境的Servlet通过HTTP GET请求对HANA XS系统执行OData $filter操作,读取响应流时,这些字段的值显示为问号。

已尝试以下操作但均未解决问题:

  • 将Java文件以UTF-8编码格式保存
  • 对响应进行UTF-8编码设置
  • 在请求头中传递Accept-Encoding和Accept-Charset为UTF-8

相同代码在本地普通Java类中运行正常,不清楚部署为Servlet时出现该问题的原因,附上代码:

URL urlObj = new URL(executeURL);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
//          connection.setRequestProperty("charset", "utf-8");
//          connection.setRequestProperty("Accept-Encoding", "utf-8");
//          connection.setRequestProperty("Accept-Charset", "Charset=windows-1255");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(userPass.getBytes()));
connection.setDoInput(true);

in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String inputLine;
StringBuffer responseStrBuffer = new StringBuffer();
while ((inputLine = (in.readLine())) != null) {
        responseStrBuffer.append(inputLine);
}

JsonParser parser = new JsonParser();
jsonObj = (JsonObject) parser.parse(responseStrBuffer.toString());

排查与解决方案

1. 强制设置BTP Neo容器的JVM编码

Servlet运行在BTP Neo容器中,容器默认字符编码可能不是UTF-8,导致字符串处理时编码丢失。在Servlet初始化方法中添加编码强制设置:

@Override
public void init() throws ServletException {
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("sun.jnu.encoding", "UTF-8");
}

2. 修正请求头格式

原注释的Accept-Charset头格式错误,正确格式应为UTF-8,且Accept-Encoding是用于压缩编码(如gzip),不要与字符编码混淆。取消注释并修正请求头:

connection.setRequestProperty("Accept-Charset", "UTF-8");

3. 验证HANA XS OData服务的响应编码

用Postman等工具直接调用OData接口,检查响应头的Content-Type是否包含charset=UTF-8。若服务未指定字符集,即使客户端设置UTF-8也会出现编码异常。

4. 优化响应流读取方式

避免逐行读取可能导致的编码截断,改用直接读取字节流并指定UTF-8编码:

String responseStr = new String(Files.readAllBytes(connection.getInputStream()), StandardCharsets.UTF_8);

5. 确认JSON解析器的编码设置

检查使用的JsonParser是否默认采用UTF-8解析。以Gson为例,显式指定编码创建解析器:

Gson gson = new GsonBuilder().setCharset(StandardCharsets.UTF_8).create();
JsonObject jsonObj = gson.fromJson(responseStrBuffer.toString(), JsonObject.class);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:22:42