I\'m working on a data transfer for a gateway which requires me to send data in UrlEncoded form. However, .net\'s UrlEncode creates lowercase tags, and it breaks the transfe
Replace the lowercase percent encoding from HttpUtility.UrlEnocde with a Regex:
static string UrlEncodeUpperCase(string value) {
value = HttpUtility.UrlEncode(value);
return Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
}
var value = "SomeWords 123 #=/ äöü";
var encodedValue = HttpUtility.UrlEncode(value);
// SomeWords+123+%23%3d%2f+%c3%a4%c3%b6%c3%bc
var encodedValueUpperCase = UrlEncodeUpperCase(value);
// now the hex chars after % are uppercase:
// SomeWords+123+%23%3D%2F+%C3%A4%C3%B6%C3%BC
I know this is very old and maybe this solution didn't exist, but this was one of the top pages I found on google when trying to solve this.
System.Net.WebUtility.UrlEncode(posResult);
This encodes to uppercase.
if anyone else gets here in search for perl code or a PCRE (perl-compatible regular expression) to solve the issue, a (candidate for the shortest possible) perl-expression to convert url-encoding to lowercase hex is:
s/%(\X{2})/%\L$1\E/go
and the other way around (lowercase to uppercase)
s/%(\x{2})/%\U$1\E/go
This is very easy
Regex.Replace( encodedString, @"%[a-f\d]{2}", m => m.Value.ToUpper() )
I.e. replace all hex letter-digit combinations to upper case
This is the code that I'm using in a Twitter application for OAuth...
Public Function OAuthUrlEncode(ByVal value As String) As String
Dim result As New StringBuilder()
Dim unreservedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
For Each symbol As Char In value
If unreservedChars.IndexOf(symbol) <> -1 Then
result.Append(symbol)
Else
result.Append("%"c + [String].Format("{0:X2}", AscW(symbol)))
End If
Next
Return result.ToString()
End Function
Hope this helps!
I think you're stuck with what C# gives you, and getting errors suggests a poorly implemented UrlDecode function on the other end.
With that said, you should just need to loop through the string and uppercase only the two characters following a % sign. That'll keep your base64 data intact while massaging the encoded characters into the right format:
public static string UpperCaseUrlEncode(string s)
{
char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
for (int i = 0; i < temp.Length - 2; i++)
{
if (temp[i] == '%')
{
temp[i + 1] = char.ToUpper(temp[i + 1]);
temp[i + 2] = char.ToUpper(temp[i + 2]);
}
}
return new string(temp);
}