Java 7中的Base64字符串解码问题

时间:2014-08-14 08:57:46

标签: java c# base64 decode apache-commons

我有一个Base64编码的字符串,我想在我的引擎中解码Java 7。 字符串是这样的:

String msg = "TwBuACAAMAAzACAATQBhAHIAIAAxADQALAAgAGEAdAAgADEAOQAyADkAaAByAHMALAAg
    AFMAeQByAGkAYQBuACAAagBlAHQAcwAgAGYAaQByAGUAZAAgADEAOAAgAHIAbwBjAGsAZQB0AHMAIA
    BhAHQAIABBAHIAcwBhAGwAJwBzACAAVwBhAGQAaQAgAEsAaABhAGkAcgAgAGEAbgBkACAAdABoAGUA
    IAByAG8AYQBkACAAYgBlAHQAdwBlAGUAbgAgAFMAbABlAGUAdABhACAAYQBuAGQAIABuAG8AcgB0AG
    gAZQByAG4AIAB0AG8AdwBuACAAbwBmACAAQQByAHMAYQBsAC0AQgBhAGEAbABiAGUAawAgAGEAcgBl
    AGEALgA=";

它来自用C#编写的Web服务。

如果我将其粘贴到网络上的任何 Base64解码器中,它可以正常工作。如果我使用 apache commons decoder ,它会给我一些奇怪的输出,其中每个字母后跟一个带问号的黑色菱形(见sreenshot)Screenshot of Output

我尝试在解码前和转换为String时设置编码,但没有成功。 这是代码:

System.setProperty("file.encoding", "UTF-8");       
String enc =
System.getProperty("file.encoding","UTF-8");
System.out.println(enc);        
String msg = "TwBuACAAMAAzACAATQBhAHIAIAAxADQALAAgAGEAdAAgADEAOQAyADkAaAByAHMALAAg
    AFMAeQByAGkAYQBuACAAagBlAHQAcwAgAGYAaQByAGUAZAAgADEAOAAgAHIAbwBjAGsAZQB0AHMAIA
    BhAHQAIABBAHIAcwBhAGwAJwBzACAAVwBhAGQAaQAgAEsAaABhAGkAcgAgAGEAbgBkACAAdABoAGUA
    IAByAG8AYQBkACAAYgBlAHQAdwBlAGUAbgAgAFMAbABlAGUAdABhACAAYQBuAGQAIABuAG8AcgB0A
    GgAZQByAG4AIAB0AG8AdwBuACAAbwBmACAAQQByAHMAYQBsAC0AQgBhAGEAbABiAGUAawAgAGEAcgB
    lAGEALgA=";

byte[] res = Base64.decodeBase64(msg);      
System.out.println(new String(res, "UTF-8"));

有什么想法吗?

亲切的问候, Kartopete

2 个答案:

答案 0 :(得分:1)

该字符串采用 UTF-16LE 编码,根据Oracle的documentation 16位Unicode(或UCS)转换格式,little-endian字节顺序。有关UTF-16变体的更多信息,请参见here

将base64字符串转换为字节后,请执行以下操作:

byte[] bytes; // base64 decoded bytes
String s = new String(bytes, "UTF-16LE");

字符串的值为:

  

3月14日,1929时,叙利亚喷气式飞机在Arsal's Wadi发射了18枚火箭弹   Khair和Sleeta和北部城镇Arsal-Baalbek之间的公路   区域。

答案 1 :(得分:0)

我在eclipse中的输出,

String msg = "TwBuACAAMAAzACAATQBhAHIAIAAxADQALAAgAGEAdAAgADEAOQAyADkAaAByAHMALAAgAFMAeQByAGkAYQBuACAAagBlAHQAcwAgAGYAaQByAGUAZAAgADEAOAAgAHIAbwBjAGsAZQB0AHMAIABhAHQAIABBAHIAcwBhAGwAJwBzACAAVwBhAGQAaQAgAEsAaABhAGkAcgAgAGEAbgBkACAAdABoAGUAIAByAG8AYQBkACAAYgBlAHQAdwBlAGUAbgAgAFMAbABlAGUAdABhACAAYQBuAGQAIABuAG8AcgB0AGgAZQByAG4AIAB0AG8AdwBuACAAbwBmACAAQQByAHMAYQBsAC0AQgBhAGEAbABiAGUAawAgAGEAcgBlAGEALgA=";
byte[] b = Base64.decodeBase64(msg);
System.out.println(new String(b));

输出

3月14日,1929时,叙利亚喷气式飞机向Arsal的Wadi Khair和Sleeta与北部城镇Arsal-Baalbek地区之间的公路发射了18枚火箭弹。