当前位置 : 主页 > 网页制作 > HTTP/TCP >

NameValuePair 简单名称值对节点类型

来源:互联网 收集:自由互联 发布时间:2021-06-16
/// summary /// 组装普通文本请求参数用于post请求 /// /summary /// param name="parameters" Key-Value形式请求参数字典 /param /// returns URL编码后的请求数据 /returns static public string BuildQuery(IDictionary st
/// <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();
        }
View Code

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
}
View Code
网友评论