如何在 Android Oreo 中获取字符串的 Base64 表示

How to obtain the Base64 representation of a string in Android Oreo

我需要在 Oreo api 级别下将字符串转换为 base64。 我有以下代码:

 public String genAuthKey(String u, String p){
    user = u;
    pass = p;
    key = user+":"+pass;
    byte[] encodedBytes = new byte[0];
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        encodedBytes = Base64.getEncoder().encode(key.getBytes());
        Log.e("VERSION IS","O");

    }else{
        encodedBytes = Base64.getEncoder().encodeToString(key.getBytes()).getBytes();
        Log.e("VERSION LESS","O");
    }
    Log.e("key",new String(encodedBytes,Charset.forName("UTF-8")));
    return new String(encodedBytes, Charset.forName("UTF-8"));

}

在其他情况下,我需要代码来正确转换和发送数据。我该怎么做?

尝试使用此代码对 kotlin 进行编码:

var encodedString = Base64.encode("Your String", Base64.DEFAULT).toString(Charsets.UTF_8)

和解码:

var decodedString = Base64.decode(encodedString, Base64.DEFAULT).toString(Charsets.UTF_8)

首先添加这个导入

import android.util.Base64;

然后用版本不可知的变体替换你的方法

public String genAuthKey(String u, String p) {
        user = u;
        pass = p;
        key = user + ":" + pass;
        byte[] encodedBytes = Base64.encode(key.getBytes(), Base64.DEFAULT);

        Log.e("key", new String(encodedBytes, StandardCharsets.UTF_8));
        return new String(encodedBytes, StandardCharsets.UTF_8);
    }

尽情享受吧!