【问题标题】:Java: Encode String in quoted-printableJava:在quoted-printable中编码字符串
【发布时间】:2014-03-01 17:40:07
【问题描述】:

我正在寻找一种方法来quoted-printable 在 Java 中编码一个字符串,就像 php 的原生 quoted_printable_encode() 函数一样。

我尝试使用 JavaMails 的 MimeUtility 库。但我无法让 encode(java.io.OutputStream os, java.lang.String encoding) 方法工作,因为它使用 OutputStream 作为输入而不是字符串(我使用函数 getBytes() 来转换字符串)并输出一些我无法返回到字符串的内容(我我是一个 Java 菜鸟 :)

谁能给我一些提示,告诉我如何编写一个将字符串转换为 OutputStream 并在编码后将结果作为字符串输出的包装器?

【问题讨论】:

标签: java jakarta-mail mime quoted-printable


【解决方案1】:

要使用这个MimeUtility 方法,您必须创建一个ByteArrayOutputStream,它将累积写入它的字节,然后您可以恢复。例如,对字符串original进行编码:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream encodedOut = MimeUtility.encode(baos, "quoted-printable");
encodedOut.write(original.getBytes());
String encoded = baos.toString();

来自同一类的 encodeText 函数可以处理字符串,但它会产生 Q 编码,即 similar to quoted-printable but not quite the same

String encoded = MimeUtility.encodeText(original, null, "Q");

【讨论】:

  • 输出 =?UTF-8?Q?H=C3=A4tte?= 而不是 MimeUtility.encodeText("Hätte", null, "Q"); 的预期 H=C3=A4tte 并且不添加换行符 - 所以它对我不起作用
  • 您是在尝试对 mime 消息标题或正文进行编码吗?
  • 我正在尝试对正文进行编码 - 但我并没有对所有内容都使用 JavaMail。我只需要引用的可打印编码。
  • 查看更新以了解使用encode 方法的方法。 Apache Commons Codec 项目也实现了quoted-printable,但它也没有添加换行符(commons.apache.org/proper/commons-codec/archives/1.9/apidocs/…
【解决方案2】:

这对我有帮助

    @Test
public void koi8r() {
    String input = "=5F=F4=ED=5F15=2E05=2E";
    String decode = decode(input, "KOI8-R", "quoted-printable", "KOI8-R");
    Assertions.assertEquals("_ТМ_15.05.", decode);
}

public static String decode(String text, String textEncoding, String encoding, String charset) {
    if (text.length() == 0) {
        return text;
    }

    try {
        byte[] asciiBytes = text.getBytes(textEncoding);
        InputStream decodedStream = MimeUtility.decode(new ByteArrayInputStream(asciiBytes), encoding);
        byte[] tmp = new byte[asciiBytes.length];
        int n = decodedStream.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return new String(res, charset);
    } catch (IOException | MessagingException e) {
        return text;
    }
}

【讨论】:

猜你喜欢
  • 2012-03-05
  • 2017-10-05
  • 1970-01-01
  • 2011-09-24
  • 2018-02-01
  • 2019-04-29
  • 2018-07-09
  • 2011-01-14
  • 1970-01-01
相关资源
最近更新 更多