简体   繁体   中英

How to decode base64 in java

I am getting a base64encoded xml data in webservice response and I want to decode it in Java . I tried org.apache.commons.codec.binary.Base64;

byte bytesEncoded[] = base64encodedStringfromWebservice.getBytes();
// Decrypt data on other side, by processing encoded data
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
System.out.println("Decoded value is " + new String(valueDecoded));

but still some characters like (< , />) are not getting decoded properly .

Please suggest how to decode it correctly?

The getBytes method from String is platform specific . You need to specify an encoding , and later use that same encoding to decode the string. You can just use UTF8.

You also need to do the steps in reverse order: string -> base64 -> raw utf8 bytes -> base64 -> string

// ENCODE data
byte bytesEncoded[] = base64encodedStringfromWebservice.getBytes("UTF8");

// DECODE data on other side, by processing encoded data
String base64encodedStringfromWebservice = new String(bytesEncoded, "UTF8");
byte[] valueDecoded = Base64.decodeBase64(base64encodedStringfromWebservice);
System.out.println("Decoded value is " + new String(valueDecoded));

Try specifiying the charset you are using. for example, utf-8, and as you can see here: Decoding a Base64 string in Java

byte[] valueDecoded= Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded, "UTF-8"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM