Ehsan Zargar Ershadi
Ehsan Zargar Ershadi

Reputation: 24853

Is there a Java equivalent for C#'s HttpServerUtility.UrlTokenEncode?

How do I encode in Java a string that is going to get decoded in C# using HttpServerUtility.UrlTokenDecode?

Upvotes: 2

Views: 708

Answers (2)

James Martin
James Martin

Reputation: 1060

The following method replicates the C# functionality.

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

Upvotes: 1

Ehsan Zargar Ershadi
Ehsan Zargar Ershadi

Reputation: 24853

After a day struggling, this simple method did the work:

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

Upvotes: 1

Related Questions