How can I make a String Base64 Url Safe Java/Android?

泪湿孤枕 提交于 2021-02-09 08:17:39

问题


I've been trying for a while but I can't seem to get my string to be Url Safe no matter what I do:

Input: XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT+d7yvxw=
Desired Output: XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT-d7yvxw

Essentially I want to apply some flags on my input string from https://developer.android.com/reference/android/util/Base64.html, namely Base64.URL_SAFE,Base64.NO_PADDING and Base64.NO_WRAP. However when I do:

String str = "XzbeW3jg9NYp6J0w2mTP4NLrTK06p1EDTnNG+KYhvyw=";

byte[] encoded = Base64.encode(
        str.getBytes(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);

byte[] strBytes = Base64.decode(encoded, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
String decoded = new String(strBytes);

//outputs original str "XzbeW3jg9NYp6J0w2mTP4NLrTK06p1EDTnNG+KYhvyw="
System.out.println(decoded);

I am not sure why the url safe encoding isn't working here, is there something I"m doing wrong? Is there a way I can get my desired output (besides manually doing String.replace() and other string modifications?


回答1:


Thanks for the comments everyone! It was correct that I already had a base64 encoded string and I needed to decode first then re-encode.

byte[] strBytes = Base64.decode(str, Base64.DEFAULT);
byte[] encoded = Base64.encode(
    strBytes, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
return new String(encoded);

is the solution that ended up working for me.




回答2:


You can archieve your desired behaviour by using an URLEncoder:

String urlEncoded = URLEncoder.encode(yourBase64String, "UTF-8");


来源:https://stackoverflow.com/questions/47123876/how-can-i-make-a-string-base64-url-safe-java-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!