Java: Encode String in quoted-printable

前端 未结 2 1961
长情又很酷
长情又很酷 2021-01-24 04:11

I am looking for a way to quoted-printable encode a string in Java just like php\'s native quoted_printable_encode() function.

I have tried to use JavaMails

相关标签:
2条回答
  • 2021-01-24 04:50

    To use this MimeUtility method you have to create a ByteArrayOutputStream which will accumulate the bytes written to it, which you can then recover. For example, to encode the string original:

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

    The encodeText function from the same class will work on strings, but it produces Q-encoding, which is similar to quoted-printable but not quite the same:

    String encoded = MimeUtility.encodeText(original, null, "Q");
    
    0 讨论(0)
  • 2021-01-24 04:59

    Thats what helps me

        @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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题