.net UrlEncode - lowercase problem

balint picture balint · May 27, 2009 · Viewed 17.6k times · Source

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 transfer (Java creates uppercase).

Any thoughts how can I force .net to do uppercase UrlEncoding?

update1:

.net out:

dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2fENVuAlDQGRNCp1F

vs Java's:

dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2FENVuAlDQGRNCp1F

(it is a base64d 3DES string, i need to maintain it's case).

Answer

Kevin picture Kevin · May 27, 2009

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