You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Android开发中java.lang.IllegalArgumentException: bad base-64错误

问题根因

从崩溃堆栈可直接定位错误来源:

  • 错误触发位置是Tools类第125行的decodeBase64方法,调用android.util.Base64.decode时传入了不符合Base64编码规则的字符串,直接抛出IllegalArgumentException: bad base-64异常
  • 调用链路为:MyApplication.onCreate -> initNotification -> requestTopic -> Tools.decrypt -> 两次调用decodeBase64
修复方案

1. 增加入参合法性校验与异常捕获

先给解码方法加防护逻辑,避免非法输入直接导致崩溃:

public static String decrypt(String code) {
    if (TextUtils.isEmpty(code)) {
        return ""; // 可替换为业务需要的默认返回值
    }
    try {
        return decodeBase64(decodeBase64(code));
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return ""; // 解码失败返回默认值
    }
}

public static String decodeBase64(String code) {
    if (TextUtils.isEmpty(code)) {
        return "";
    }
    try {
        byte[] valueDecoded = Base64.decode(code.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
        return new String(valueDecoded, StandardCharsets.UTF_8);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return "";
    }
}

2. 校验解码入参合法性

到MyApplication类第88行的requestTopic方法中,检查传入Tools.decrypt()的原始字符串:

  • 确认字符串是否为合法Base64编码,有没有多余的空格、换行、特殊字符
  • 确认编码时使用的flag与解码时一致,若编码时用了Base64.NO_WRAP/Base64.URL_SAFE等特殊flag,解码时必须使用相同flag才能正常解析

3. URL安全Base64适配

如果待解码的是URL安全格式的Base64字符串(+替换为-、/替换为_、删除了末尾=补位符),需要做格式适配再解码:

public static String decodeBase64(String code) {
    if (TextUtils.isEmpty(code)) {
        return "";
    }
    try {
        // 补全末尾补位符
        String modifiedCode = code;
        int paddingCount = (4 - modifiedCode.length() % 4) % 4;
        if (paddingCount > 0) {
            modifiedCode += "=".repeat(paddingCount);
        }
        // 替换URL安全字符为标准Base64字符
        modifiedCode = modifiedCode.replace('-', '+').replace('_', '/');
        byte[] valueDecoded = Base64.decode(modifiedCode.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
        return new String(valueDecoded, StandardCharsets.UTF_8);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return "";
    }
}

内容的提问来源于stack exchange,提问作者atozcodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:45:03