首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#的HttpServerUtility.UrlTokenDecode是否有Java的等效值?

C#的HttpServerUtility.UrlTokenDecode是否有Java的等效值?
EN

Stack Overflow用户
提问于 2014-02-09 08:39:00
回答 1查看 976关注 0票数 3

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-09 09:10:47

我尝试使用org.apache.commons.codec.binary.Base64 ( ctor接受一个参数,说明编码/解码是否是url安全的),但结果发现它的实现方式与UrlTokenEncode/Decode不同。

最后,我将C#实现迁移到Java:

代码语言:javascript
复制
 public static byte[] UrlTokenDecode(String input) { 
    if (input == null)
        return new byte[0];

    int len = input.length(); 
    if (len < 1)
        return new byte[0]; 

    ///////////////////////////////////////////////////////////////////
    // Step 1: Calculate the number of padding chars to append to this string. 
    //         The number of padding chars to append is stored in the last char of the string.
    int numPadChars = (int)input.charAt(len - 1) - (int)'0';
        if (numPadChars < 0 || numPadChars > 10)
            return null; 


    /////////////////////////////////////////////////////////////////// 
    // Step 2: Create array to store the chars (not including the last char)
    //          and the padding chars 
    char[] base64Chars = new char[len - 1 + numPadChars];


    //////////////////////////////////////////////////////// 
    // Step 3: Copy in the chars. Transform the "-" to "+", and "*" to "/"
    for (int iter = 0; iter < len - 1; iter++) { 
        char c = input.charAt(iter); 

        switch (c) { 
            case '-':
                base64Chars[iter] = '+';
                    break;

                case '_':
                base64Chars[iter] = '/'; 
                break; 

            default: 
                base64Chars[iter] = c;
                break;
        }
    } 

    //////////////////////////////////////////////////////// 
    // Step 4: Add padding chars 
    for (int iter = len - 1; iter < base64Chars.length; iter++) {
        base64Chars[iter] = '='; 
    }

    // Do the actual conversion
    String assembledString = String.copyValueOf(base64Chars);
    return Base64.decodeBase64(assembledString);
}   
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21657024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档