【问题标题】:Weird encoding issue with AWS ec2 - javaAWS ec2 的奇怪编码问题 - java
【发布时间】:2021-01-25 06:44:50
【问题描述】:

我有一个 Java Spring Boot 应用程序,该应用程序在本地响应编码良好的文本:

Battle Is Lord's by Rebecca St. James (Ft. Brandon Lake)

但是当我在我的 AWS 实例 (ec2) 上运行应用程序时,它会返回:

Battle Is the Lord's by丽贝卡圣。詹姆斯(Ft.��Brandon��Lake)

这是我的 apache HttpClient 设置:

...
public class HttpClientHandler {

    public  String getHandler(final String url) {
        return getHandler(url, null);
    }

    public  String getHandler(final String url, final String authHeader) {

        final StringBuilder apiResponse = new StringBuilder();

        final HttpClient client = HttpClientBuilder.create().build();
        log.info("Get url: {}, with authHeader: {}", url, authHeader);
        final HttpGet request = new HttpGet(url);
        request.addHeader("Content-Type", "application/json");

        if (authHeader != null && !authHeader.isEmpty()) {
            request.addHeader("Authorization", authHeader);
        }


        try {
            final HttpResponse response = client.execute(request);
            log.info("Response Code : {}", response.getStatusLine().getStatusCode());
            final BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

            String line;
            while ((line = rd.readLine()) != null) {
                apiResponse.append(line);
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return apiResponse.toString();
    }

}

我特别困惑,因为我在本地运行应用程序时发现它运行良好。

感谢您的帮助,

瑞克

【问题讨论】:

  • 验证标题中是否有与内容类型相关的内容。类似Content-Type: text/html; charset=utf-8
  • 我设置了 request.addHeader("Content-Type", "application/json");在回复中没有其他内容类型
  • 您可以尝试为InputStreamReader 提供特定的字符集吗?默认字符集是使用底层操作系统区域设置确定的。不知道你的EC2是怎么配置的。
  • 是的,这就是解决方案,感谢@tzortzik!我需要指定 InputStreamReader。

标签: java amazon-web-services spring-boot amazon-ec2 character-encoding


【解决方案1】:

InputStreamReader 可以接受字符集参数。如果未指定,则将使用运行 JVM 的语言环境来确定字符集。解码消息时,它的编码必须与输入编码具有相同的格式。

下面的例子都是用 Kotlin 写的,但是思路是一样的

从一个字符集转换为另一个:

val s = "Battle Is the Lord's by Rebecca St. James (Ft. Brandon Lake)"
val inputStream = s.byteInputStream(Charsets.UTF_8)
val reader = InputStreamReader(inputStream, Charsets.UTF_16)
val lines = BufferedReader(reader).readLines()
println(lines)

将返回[??????????]

读取相同字符集中的数据将导致正确读取数据

val s = "your initial string"
val inputStream = s.byteInputStream(Charsets.UTF_8)
val reader = InputStreamReader(inputStream, Charsets.UTF_16)
val lines = BufferedReader(reader).readLines()
println(lines)

会写[your initial string]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    相关资源
    最近更新 更多