c# - 是否有 C# 的 HttpServerUtility.UrlTokenDecode 的 Java 等效项?

标签 c# java url-encoding

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

最佳答案

我尝试使用 org.apache.commons.codec.binary.Base64(ctor 接受一个参数,说明编码/解码是否是 url 安全的)但事实证明它没有实现相同作为 UrlTokenEncode/Decode。

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

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

关于c# - 是否有 C# 的 HttpServerUtility.UrlTokenDecode 的 Java 等效项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657024/

相关文章:

java - 我应该使用什么 Maven 存储库来获取 tomcat jar?

java - Controller 中未检测到 freemarker 形式的 Spring 绑定(bind)

url - 从浏览器地址栏中复制 UTF-8 URL,只给出丑陋的编码 URL

javascript - 发送请求时可以urlencode null吗?

c# - 回发后 jquery 不工作

c# - 有序区别

c# - 以设计器模式打开 .NET 表单 - 获取 "The path is not of a legal form"

c# - 将从部门检索到的 SQL 值分配给 session ["UserAuthentication"]

java - 重写的私有(private)方法导致在Java中访问子类公共(public)方法时出现异常

java - 在 Java 中,在发送 JSON POST 时使用 HttpPost(apache commons HttpClient)——我应该对正文进行 URL 编码吗?