C# HttpUtility.UrlEncode(param_body, Encoding.) ui
是"%7b%22order_no%22%3a%228781442235161190%22%2c%22status%22%3a%222000%22%7d461de5b941e9622585cc8c184f65aef6"編碼
而JAVA URLEncoder.encode(param_body, "utf-8") url
%7B%22order_no%22%3A%228781442235161190%22%2C%22status%22%3A%222000%22%7D461de5b941e9622585cc8c184f65aef6code
status並無變,只是Encoder部分產生的代碼 C#用的小寫,而JAVA用的是大寫
utf-8
UrlEncode不會對「*」進行編碼,若是須要,需手動將「*」替換爲「%2A」字符串
方式一string
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();
}
it
方式二io
#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