C# HttpUtility.UrlEncode 与 JAVA URLEncoder.encode 区别

C# HttpUtility.UrlEncode(param_body, Encoding.) 

是"%7b%22order_no%22%3a%228781442235161190%22%2c%22status%22%3a%222000%22%7d461de5b941e9622585cc8c184f65aef6"

 

而JAVA URLEncoder.encode(param_body, "utf-8") 

%7B%22order_no%22%3A%228781442235161190%22%2C%22status%22%3A%222000%22%7D461de5b941e9622585cc8c184f65aef6

 

status并没有变,只是Encoder部分产生的代码 C#用的小写,而JAVA用的是大写

UrlEncode不会对“*”进行编码,如果需要,需手动将“*”替换为“%2A”

方式一

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

方式二

#region UrlEncode(对Url进行编码)

/// <summary>
/// 对Url进行编码
/// </summary>
/// <param name="url">url</param>
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
public static string UrlEncode(string url, bool isUpper = false)
{
return UrlEncode(url, Encoding.UTF8, isUpper);
}

/// <summary>
/// 对Url进行编码
/// </summary>
/// <param name="url">url</param>
/// <param name="encoding">字符编码</param>
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
{
var result = HttpUtility.UrlEncode(url, encoding);
if (!isUpper)
return result;
return GetUpperEncode(result);
}

/// <summary>
/// 获取大写编码字符串
/// </summary>
/// <param name="encode">字串</param>
/// <returns></returns>
private static string GetUpperEncode(string encode)
{
var result = new StringBuilder();
int index = int.MinValue;
for (int i = 0; i < encode.Length; i++)
{
string character = encode[i].ToString();
if (character == "%")
index = i;
if (i - index == 1 || i - index == 2)
character = character.ToUpper();
result.Append(character);
}
return result.ToString();
}

#endregion

posted on 2019-03-21 16:29  zhusk  阅读(985)  评论(0编辑  收藏  举报

导航