【问题标题】:Java Base64 Decoding/Encoding rountrip doesn't come up with same resultJava Base64 解码/编码往返没有得出相同的结果
【发布时间】:2016-06-21 12:42:31
【问题描述】:
import org.junit.Test;
import java.util.Base64;
import org.junit.Assert.*;
import java.util.Random;

...

@Test
public void testEncoding(){
    byte[] data = new byte[32];
    new Random().nextBytes(data);
    String base64 = Base64.getEncoder().encodeToString(data);
    assertEquals(data, Base64.getDecoder().decode(base64));
}

@Test
public void testDecoding(){
    String base64 = "ABCDEFGHIJKLRMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A==";
    byte[] data = Base64.getDecoder().decode(base64);
    assertEquals(base64, Base64.getEncoder().encodeToString(data));
}

testEncoding 测试失败并出现 AssertionError: 预期:[B@6bf2d08e 实际:[B@5eb5c224 我不明白为什么。

【问题讨论】:

  • 你确定assertEquals(byte[], byte[]) 做你想做的事吗?数组自然不会实现相等...

标签: java encoding base64 decoding


【解决方案1】:

缺陷在 then Assertion 而不是在代码中。

assertEquals 会比较字节数组在内存中的地址 assertArrayEquals 会比较字节数组的内容

【讨论】:

    【解决方案2】:

    试试这个。你应该编码一个普通的字符串,解码一个普通的字符串,而不是一个字节数组:

    @Test
    public void verify() throws Exception {
        String normalString = "ABCDEFGHIJKLRMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A==";
        byte[] asBytes = normalString.getBytes();
        String encoded = Base64.getEncoder().encodeToString(asBytes);
        byte[] decodedBytes = Base64.getDecoder().decode(encoded);
        String decoded = new String(decodedBytes);
    
        assertEquals(normalString , decoded);
    }
    

    【讨论】:

    • 我需要对文件进行编码和解码,以便在电子邮件中发送它们并作为 HTTP 请求的参数。我也需要它来处理字节数组或 InputStreams。 encodeToString 的方法签名也需要一个字节数组。如果我使用 .getBytes() 那么我仍然会得到一个断言错误。预期:[B@50134894 实际:[B@2957fcb0
    • base64编码的object是将任意二进制数据编码为文本。
    • @TomVanRossom 无法转换为/从您平台的默认编码转换的字节/字节序列怎么办?
    猜你喜欢
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2013-03-20
    相关资源
    最近更新 更多