C# 对字符串进行UrlEncode/UrlDecode

https://www.cnblogs.com/li150dan/p/13492280.html

 

//对字符进行UrlEncode编码
string text= System.Web.HttpUtility.UrlEncode("heart", System.Text.Encoding.UTF8);    
//对字符进行UrlDecode解码
string data = System.Web.HttpUtility.UrlDecode(text, System.Text.Encoding.UTF8); 

在c#中,HttpUtility.UrlEncode("www+mzwu+com")编码结果为www%2bmzwu%2bcom,在和Java开发的平台做对接的时候,对方用用url编码后再对其进行MD5加密,url编码之后的字符串为大(www%2Bmzwu%2Bcom)写这样加密出来的字符串就.net平台的不匹配,

以下供上方法就是解决HttpUtility.UrlEncode编码由小写转化为大写字母
/// <summary>
    /// 对字符进行UrlEncode编码
    /// string转Encoding格式
    /// </summary>
    /// <param name="text"></param>
    /// <param name="encod">编码格式</param>
    /// <param name="cap">是否输出大写字母</param>
    /// <returns></returns>
    public static string UrlEncode(string text, Encoding encod, bool cap = true)
    {
      if(cap)
      {
        StringBuilder builder = new StringBuilder();
        foreach (char c in text)
        {
          if (System.Web.HttpUtility.UrlEncode(c.ToString(), encod).Length > 1)
          {
            builder.Append(System.Web.HttpUtility.UrlEncode(c.ToString(), encod).ToUpper());
          }
          else
          {
            builder.Append(c);
          }
        }
        return builder.ToString();
      }
      else
      {
        string encodString = System.Web.HttpUtility.UrlEncode(text, encod);
        return encodString;
      }
    }

    /// <summary>
    /// 对字符进行UrlDecode解码
    /// Encoding转string格式
    /// </summary>
    /// <param name="encodString"></param>
    /// <param name="encod">编码格式</param>
    /// <returns></returns>
    public static string UrlDecode(string encodString, Encoding encod)
    {
      string text = System.Web.HttpUtility.UrlDecode(encodString, encod);
      return text;
    }

 

posted @ 2023-03-22 11:40  LuoCore  阅读(3402)  评论(0编辑  收藏  举报