C#的HttpServerUtility.UrlTokenEncode是否有Java等价物?

时间:2016-01-05 13:47:51

标签: java c# android url-encoding

如何使用HttpServerUtility.UrlTokenDecode在Java中编码将在C#中解码的字符串?

2 个答案:

答案 0 :(得分:0)

经过一天的努力,这个简单的方法完成了工作:

public string ToUnsafeUrl(this string str)
    {
        if (str == null)
            return null;
        return str.Replace("-", "+").Replace("_", "/");
    }

答案 1 :(得分:0)

以下方法复制C#功能。

public static String urlTokenEncode(String inputString) {
    if (inputString == null) {
        return null;
    }
    if (inputString.length() < 1) {
        return null;
    }

    // Step 1: Do a Base64 encoding
    String base64Str = new String(java.util.Base64.getEncoder().encode(inputString.getBytes()));

    // Step 2: Transform the "+" to "-", and "/" to "_"
    base64Str = base64Str.replace('+', '-').replace('/', '_');

    // Step 3: Find how many padding chars are present at the end
    int endPos = base64Str.lastIndexOf('=');
    char paddingChars = (char)((int)'0' + base64Str.length() - endPos);

    // Step 4: Replace padding chars with count of padding chars
    char[] base64StrChars = base64Str.toCharArray();
    base64StrChars[endPos] = paddingChars;

    return new String(base64StrChars);
}