简体   繁体   English

如何制作String Base64 Url Safe Java / Android?

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

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: 我已经尝试了一段时间,但无论我做什么,我似乎无法将我的字符串作为Url Safe:

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 . 基本上我想在https://developer.android.com/reference/android/util/Base64.html的输入字符串上应用一些标志,即Base64.URL_SAFEBase64.NO_PADDINGBase64.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? 我不知道为什么url安全编码在这里不起作用,有什么我做错了吗?有没有办法可以得到我想要的输出(除了手动做String.replace()和其他字符串修改?

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. 我已经有了base64编码的字符串是正确的,我需要首先解码然后重新编码。

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. 是最终为我工作的解决方案。

您可以使用URLEncoder来实现您想要的行为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM