【问题标题】:â® characters getting converted to question marks while getting backâ® 字符在返回时转换为问号
【发布时间】:2016-11-27 22:08:19
【问题描述】:

我遇到了一个非常奇怪的问题。 我正在从 Amazon AWS SQS 发送和获取消息。 在放置时,我正在压缩和编码消息,如下所示:

String responseMessageBodyOriginal = gson.toJson(responseData);
String responseMessageBodyCompressed = compressToBase64String(responseMessageBodyOriginal);
AmazonSqsHelper.sendMessage(responseMessageBodyCompressed, queue, null);

压缩和编码函数,如下所示:

public static String compressToBase64String(String data) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
    GZIPOutputStream gzip = new GZIPOutputStream(bos);
    gzip.write(data.getBytes());
    gzip.close();
    byte[] compressedBytes = bos.toByteArray();
    bos.close();
    return new String(Base64.encodeBase64(compressedBytes));
}

另一方面,在接收消息时,这是代码:

List<Message> sqsMessageList = AmazonSqsHelper.receiveMessages(queueUrl, max_message_read_count,
                    default_visibility_timeout);
int num_messages = sqsMessageList.size();
if (num_messages > 0) {
   for (Message m : sqsMessageList) {
       String responseMessageBodyCompressed = m.getBody();
       String responseMessageBodyOriginal = decompressFromBase64String(responseMessageBodyCompressed);
   }
}

而用于解码和解压的函数是这样的:

public static String decompressFromBase64String(String compressedString) throws IOException {
    byte[] compressedBytes = Base64.decodeBase64(compressedString);
    ByteArrayInputStream bis = new ByteArrayInputStream(compressedBytes);
    GZIPInputStream gis = new GZIPInputStream(bis);
    BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    gis.close();
    bis.close();
    return sb.toString();
}

但问题是,有时如果我传递诸如“â®”之类的字符,那么这些字符会被转换为 ???? , 如果我正在打印消息,则在解码后。

无法弄清楚为什么编码和解码的行为很奇怪。任何帮助将不胜感激。

【问题讨论】:

  • 你了解ASCII和Unicode的区别吗,Unicode是怎么用UTF-8编码的?如果没有,请查看维基百科。您的处理流中某处存在不匹配,其中数据以一种方式编码但以不同方式解码。
  • 什么是â®?那是两个 Unicode 代码点 (0xe2 0xae) 吗?或者,它是 UTF-8 编码吗?如果是后者则无效,因为0xe2 表示 3 字节编码的开始。这些数据是从哪里来的?在不知道您认为这些字符代表什么的情况下,实际上不可能确定您的问题出在哪里。
  • @JimGarrison 这些是 URL。 URL 包含这些字符。我知道区别:) 而且我确保编码和解码以相同的方式完成。例如:amazon.com/…
  • @JimGarrison 你能找到可能发生这种情况的地方吗?不过提前谢谢:)
  • 我们无法提供帮助,因为我们不知道 Amazon SQS 上发生了什么。问题可能就在那里。我会先保存 compressed 流并逐字节比较它们,看看是否有变化。

标签: java amazon-web-services encoding compression amazon-sqs


【解决方案1】:

问题是使用平台的默认字符集 (data.getBytes()) 进行编码,而解码 - 使用 UTF-8。

compressToBase64String 中将data.getBytes() 更改为data.getBytes(StandardCharsets.UTF_8)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多