Tag Archives: System.Web.HttpUtility.UrlEncode

Transcoding of system.web.httputility.urlencode in C #

Recently, we need to interface with Java program. The URL transcoding problem we encountered is as follows:

The characters generated by urlencoder.encode used in Java URL encoding are uppercase, and the English ‘(‘, ”) are converted to ‘(‘, ‘) 28’ and ‘(‘) 29 ‘ respectively

However, the characters generated by httputility.urlencode in c#are lowercase and the English brackets are not transcoded , so the characters generated by the two are inconsistent, leading to system errors

The solution is posted below:

1. Character case problem:

//Uppercase conversion of transcoded characters does not convert parameters to uppercase (used)
 public static string GetUpperEncode(string encodeUrl)
        {
            var result = new StringBuilder();
            int index = int.MinValue;
            for (int i = 0; i < encodeUrl.Length; i++)
            {
                string character = encodeUrl[i].ToString();
                if (character == "%")
                    index = i;
                if (i - index == 1 || i - index == 2)
                    character = character.ToUpper();
                result.Append(character);
            }
            return result.ToString();
        }
//Other methods searched on the web, by this method instead of calling HttpUtility.UrlEncode directly
private static string UrlEncode(string temp, Encoding encoding)
    {
      StringBuilder stringBuilder = new StringBuilder();
      for (int i = 0; i < temp.Length; i++)
      {
        string t = temp[i].ToString();
        string k = HttpUtility.UrlEncode(t, encoding);
        if (t == k)
        {
          stringBuilder.Append(t);
        }
        else
        {
          stringBuilder.Append(k.ToUpper());
        }
      }
      return stringBuilder.ToString();
    }

2. English bracket question:

//Solved by replacing the string
encodeurl= encodeurl.Replace("(","%28");
encodeurl=encodeurl.Replace(")", "%29");