如何使String Base64 Url安全Java/Android? [英] How can I make a String Base64 Url Safe Java/Android?

查看:84
本文介绍了如何使String Base64 Url安全Java/Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了一段时间,但是无论我做什么,我似乎都无法使我的字符串成为Url Safe:

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

基本上,我想在 https://的输入字符串上应用一些标志developer.android.com/reference/android/util/Base64.html ,即 Base64.URL_SAFE Base64.NO_PADDING Base64.NO_WRAP .但是,当我这样做时:

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);

我不确定为什么url安全编码在这里不起作用,我做错了什么吗?有没有一种方法可以获取所需的输出(除了手动执行 String.replace()和其他字符串修改?

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?

推荐答案

感谢大家的评论!没错,我已经有一个base64编码的字符串,我需要先解码然后再编码.

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.

这篇关于如何使String Base64 Url安全Java/Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆