Search code examples
javaandroidbase64url

How to use Base64.getUrlEncoder in Android Lollipop


How can i get the same result of this method using a lower Build.VERSION.SDK_INT in android:

@RequiresApi(api = Build.VERSION_CODES.O)
String result1 = "https://1drv.ms/u/s!AkijuZglD51udjvlclZWSNf_2wo";
String aa = Base64.getUrlEncoder()
                    .withoutPadding()
                    .encodeToString(result1.getBytes(StandardCharsets.UTF_8));

Output is this : https://api.onedrive.com/v1.0/shares/u!aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBa2lqdVpnbEQ1MXVkanZsY2xaV1NOZl8yd28/root/content

This code works fine but the issues is it requires android version oreo or higher but my application minimum sdk is Lollipop is it possible to get the same result but with a code that will work on lower version of android anything from Lollipop and above? Thanks


Solution

  • You would want to use android.util.Base64 encodeToString(byte[] input, int flags)

    It has been available since Android 2.2.X Froyo/API level 8.

    You would use it like:

    android.util.Base64.encodeToString(YOUR_BYTE_ARRAY, android.util.Base64.URL_SAFE | android.util.Base64.NO_PADDING);
    

    Most importantly for your use case is the android.util.Base64.URL_SAFE and android.util.Base64.NO_PADDING flags.