C#实现Java版的UrlEncode方法
以字符串“/v1/api/items”为例,C#的HttpUtility.UrlEncode的结果是“%2fv1%2fapi%2fitems”,Java的URLEncoder.encode(value, "UTF-8")的结果是“%2Fv1%2Fapi%2Fitems”,有时候对接java版的接口时候用到加密这块的话,就会很尴尬,愣是发送不成功,所以只能用C#造轮子了,实现方法如下:
public static string encode(string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { if (HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).Length > 1) { sb.Append(HttpUtility.UrlEncode(c.ToString(),Encoding.UTF8).ToUpper()); } else { sb.Append(c); } } return sb.ToString(); }