Base64 Encoding: Illegal base64 character 3c

左心房为你撑大大i 提交于 2019-12-05 08:50:20

Just use this method

getMimeDecoder()

String data = "......";
byte[] dataBytes =  Base64.getMimeDecoder().decode(data);

I got this same error and problem was that the string was starting with data:image/png;base64, ...

The solution was:

byte[] imgBytes = Base64.getMimeDecoder().decode(imgBase64.split(",")[1]);

You should first get the bytes out of the string (in some character encoding).

For these bytes you use the encoder to create the Base64 representation for that bytes.

This Base64 string can then be decoded back to bytes and with the same encoding you convert these bytes to a string.

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Example {

  public static void main(String[] args) {
    final String xml = "<root-node><sub-node/></root-node>";
    final byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    final String xmlBase64 = Base64.getEncoder().encodeToString(xmlBytes);
    System.out.println(xml);
    System.out.println(xmlBase64);

    final byte[] xmlBytesDecoded = Base64.getDecoder().decode(xmlBase64);
    final String xmlDecoded = new String(xmlBytesDecoded, StandardCharsets.UTF_8);
    System.out.println(xmlDecoded);
  }

}

Output is:

<root-node><sub-node/></root-node>
PHJvb3Qtbm9kZT48c3ViLW5vZGUvPjwvcm9vdC1ub2RlPg==
<root-node><sub-node/></root-node>

Thanks to @luk2302 I was able to resolve the issue. Before decoding the string, I need to first encode it to Base64

    byte[] dataBytes = Base64.getEncoder().encode(data.getBytes());
    dataBytes = Base64.getDecoder().decode(dataBytes);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!