/// <summary> /// 组装普通文本请求参数用于post请求 /// </summary> /// <param name="parameters">Key-Value形式请求参数字典</param> /// <returns>URL编码后的请求数据</returns> static public string BuildQuery(IDictionary<string, string> parameters) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略参数名或参数值为空的参数 if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value)) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); postData.Append(Uri.EscapeDataString(value)); hasParam = true; } } return postData.ToString(); }
Uri.EscapeDataString
publicvoid UrlEncodeTest() { string url ="C++ C#"; Console.WriteLine(HttpUtility.UrlEncode(url));//C%2b%2b+C%23 Console.WriteLine(HttpUtility.UrlPathEncode(url));//C++%20C# Console.WriteLine(Uri.EscapeUriString(url));//C++%20C# Console.WriteLine(Uri.EscapeDataString(url));//C%2B%2B%20C%23 }