C# 构造post参数一种看起来直观点的方法[转]

时间:2023-03-09 16:11:45
C# 构造post参数一种看起来直观点的方法[转]

因为本人经常爱用C#做一些爬虫类的小东西,每次构造post参数的时候,都是直接字符串拼接的方式的,有时候改起来不太方便。

场景:

需要post一个地址

参数列表 :

username:管理员

password:123456

xxx:xxx

我想大部分人可能会这样写

  1. string username = "管理员";
  2. string password = "123456";
  3. string xxx = "xxx";
  4. string postdata = string.Format("username={0}&password={1}&xxx={2}", username, password, xxx);

直接用字符串来拼接的,这样写是最直接的,我一直都是这样写,然后到后来,比如参数十几二十个的时候,不知道{7}跟{8}是谁,甚至有时候password手滑打成了pasword

碰到这些情况很蛋疼,因为这样并不怎么直观。

然后我想到了下面的方法

首先是定义了一个静态方法,方便调用,注意参数类型

此方法2.0版本以上都是支持的。

  1. public static string CreatePostData(Dictionary<string, string> PostParameters)
  2. {
  3. string postdata = string.Empty;
  4. foreach (var item in PostParameters)
  5. {
  6. if (postdata != string.Empty)
  7. postdata += "&";
  8. postdata += item.Key + "=" + item.Value;
  9. }
  10. return postdata;
  11. }

然后还有Linq版的,需要3.5版本以上不罗嗦

  1. public static string CreatePostData(Dictionary<string, string> PostParameters)
  2. {
  3. var query = from s in PostParameters select s.Key + "=" + s.Value;
  4. string[] parameters = query.ToArray<string>();
  5. return string.Join("&", parameters);
  6. }

甚至还可以写成扩展方法,这里就不写了。

然后构造post参数的时候就可以这样

  1. Dictionary<string, string> parameters = new Dictionary<string, string>();
  2. parameters.Add("username", "管理员");
  3. parameters.Add("password", "123456");
  4. parameters.Add("xxx", "xxx");
  5. string postdata = CreatePostData(parameters);

因为post参数是键值对应的,这里用字典的形式来表示出来,我个人感觉应该是蛮直观了,以后需要修改哪个参数,直接定位

代码运行结果:

C# 构造post参数一种看起来直观点的方法[转]

当然,有时候我们POST参数包含中文啊或者一些敏感字符,就需要进行urlencode了,下面是方法

  1. //此方法需要添加System.Web引用 程序集:System.Web(在 system.web.dll 中)
  2. //参数IsEncode 默认为 false 表示不需要转码,需要转码的时候指定参数为True即可
  3. public static string CreatePostData(Dictionary<string, string> PostParameters,bool IsEncode = false)
  4. {
  5. var query = from s in PostParameters select s.Key + "=" + (IsEncode ? System.Web.HttpUtility.UrlEncode(s.Value) : s.Value);
  6. string[] parameters = query.ToArray<string>();
  7. return string.Join("&", parameters);
  8. }
  1. Dictionary<string, string> parameters = new Dictionary<string, string>();
  2. parameters.Add("username", "管理员");
  3. parameters.Add("password", "123456");
  4. parameters.Add("xxx", "xxx");
  5. string postdata = CreatePostData(parameters,true);

代码运行结果:

C# 构造post参数一种看起来直观点的方法[转]

 

到这里应该差不多了,有什么不对的地方希望各位能指正出来。

原文地址:http://blog.****.net/qq807081817/article/details/38053011