Base64 Encoding: Illegal base64 character 3c

2020-08-19 03:40发布

I am trying to decode data in an xml format into bytes base64 and I am having an issues. My method is in java which takes a String data and converts it into bytes like as bellow.

String data = "......"; //string of data in xml format
byte[] dataBytes = Base64.getDecoder().decode(data);

Which failed and gave the exception like bellow.

java.lang.IllegalArgumentException: Illegal base64 character 3c
    at java.util.Base64$Decoder.decode0(Base64.java:714)
    at java.util.Base64$Decoder.decode(Base64.java:526)
    at java.util.Base64$Decoder.decode(Base64.java:549)
    at XmlReader.main(XmlReader.java:61)

Is the xml format not compatible with base64?

4条回答
Melony?
2楼-- · 2020-08-19 03:55

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>
查看更多
时光不老,我们不散
3楼-- · 2020-08-19 03:56

Just use this method

getMimeDecoder()

String data = "......";
byte[] dataBytes =  Base64.getMimeDecoder().decode(data);
查看更多
等我变得足够好
4楼-- · 2020-08-19 03:57

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]);
查看更多
冷血范
5楼-- · 2020-08-19 04:05

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);
查看更多
登录 后发表回答