FormPost.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. namespace MOKA_Factory_Tools
  7. {
  8. /// <summary>
  9. /// 表单post
  10. /// </summary>
  11. class FormPost
  12. {
  13. /// <summary>
  14. /// post数据
  15. /// </summary>
  16. /// <param name="strUrl"></param>
  17. /// <param name="postParaList"></param>
  18. /// <param name="isFile">true:用multipart/form-data发送,false:默认格式</param>
  19. /// <returns></returns>
  20. public static string postMessage(string strUrl, int timeout, List<PostDateClass> postParaList, bool isFile = false)
  21. {
  22. if (isFile == true)
  23. {
  24. #region http retry 3次机制;
  25. Func<string, List<PostDateClass>, int, string> _postMessage = (url, postlist, timeout) =>
  26. {
  27. bool status;
  28. string strReturn = "";
  29. for (int i = 0; i < 3; i++)
  30. {
  31. strReturn = postFileMessage(url, postlist, out status, timeout);
  32. if (status == true)
  33. break;
  34. }
  35. return strReturn;
  36. };
  37. return _postMessage(strUrl, postParaList, timeout);
  38. #endregion
  39. }
  40. else
  41. {
  42. StringBuilder strPost = new StringBuilder();
  43. for (int i = 0; i < postParaList.Count; i++)
  44. {
  45. if (i != 0)
  46. {
  47. strPost.Append("&");
  48. }
  49. strPost.Append(postParaList[i].Prop);
  50. strPost.Append("=");
  51. strPost.Append(postParaList[i].Value);
  52. }
  53. #region http retry 3次机制;
  54. Func<string, string, string> _postMessage = (url, poststring) =>
  55. {
  56. string strReturn = "";
  57. for (int i = 0; i < 3; i++)
  58. {
  59. strReturn = postMessage(url, poststring);
  60. if (strReturn != null)
  61. break;
  62. }
  63. return strReturn;
  64. };
  65. return _postMessage(strUrl, strPost.ToString());
  66. #endregion
  67. }
  68. }
  69. public static string postFileMessage(string strUrl, List<PostDateClass> postParaList,out bool status,int timeout)
  70. {
  71. try
  72. {
  73. status = true;
  74. string responseContent = "";
  75. var memStream = new MemoryStream();
  76. var webRequest = (HttpWebRequest)WebRequest.Create(strUrl);
  77. // 边界符
  78. var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
  79. // 边界符
  80. var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
  81. // 最后的结束符
  82. var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
  83. memStream.Write(beginBoundary, 0, beginBoundary.Length);
  84. // 设置属性
  85. webRequest.Method = "POST";
  86. webRequest.Timeout = timeout;
  87. webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
  88. webRequest.Proxy = null;
  89. for (int i = 0; i < postParaList.Count; i++)
  90. {
  91. PostDateClass temp = postParaList[i];
  92. if (temp.Type == 1)
  93. {
  94. var fileStream = new FileStream(temp.Value, FileMode.Open, FileAccess.Read);
  95. // 写入文件
  96. const string filePartHeader =
  97. "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
  98. "Content-Type: application/octet-stream\r\n\r\n";
  99. var header = string.Format(filePartHeader, temp.Prop, temp.Value);
  100. var headerbytes = Encoding.UTF8.GetBytes(header);
  101. memStream.Write(headerbytes, 0, headerbytes.Length);
  102. var buffer = new byte[1024];
  103. int bytesRead; // =0
  104. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  105. {
  106. memStream.Write(buffer, 0, bytesRead);
  107. }
  108. string end = "\r\n";
  109. headerbytes = Encoding.UTF8.GetBytes(end);
  110. memStream.Write(headerbytes, 0, headerbytes.Length);
  111. fileStream.Close();
  112. }
  113. else if (temp.Type == 0)
  114. {
  115. // 写入字符串的Key
  116. var stringKeyHeader = "Content-Disposition: form-data; name=\"{0}\"" +
  117. "\r\n\r\n{1}\r\n";
  118. var header = string.Format(stringKeyHeader, temp.Prop, temp.Value);
  119. var headerbytes = Encoding.UTF8.GetBytes(header);
  120. memStream.Write(headerbytes, 0, headerbytes.Length);
  121. }
  122. if (i != postParaList.Count - 1)
  123. memStream.Write(beginBoundary, 0, beginBoundary.Length);
  124. else
  125. // 写入最后的结束边界符
  126. memStream.Write(endBoundary, 0, endBoundary.Length);
  127. }
  128. webRequest.KeepAlive = false;
  129. System.Net.ServicePointManager.DefaultConnectionLimit = 100;
  130. //webRequest.ContentLength = memStream.Length;
  131. var requestStream = webRequest.GetRequestStream();
  132. memStream.Position = 0;
  133. var tempBuffer = new byte[memStream.Length];
  134. memStream.Read(tempBuffer, 0, tempBuffer.Length);
  135. memStream.Close();
  136. requestStream.Write(tempBuffer, 0, tempBuffer.Length);
  137. requestStream.Close();
  138. using (HttpWebResponse res = (HttpWebResponse)webRequest.GetResponse())
  139. {
  140. using (Stream resStream = res.GetResponseStream())
  141. {
  142. byte[] buffer = new byte[1024];
  143. int read;
  144. while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0)
  145. {
  146. responseContent += Encoding.UTF8.GetString(buffer, 0, read);
  147. }
  148. }
  149. res.Close();
  150. }
  151. return responseContent;
  152. }
  153. catch (Exception e)
  154. {
  155. status = false;
  156. GC.Collect();
  157. return e.Message;
  158. }
  159. }
  160. public static string postMessage(string strUrl, string strPost)
  161. {
  162. try
  163. {
  164. CookieContainer objCookieContainer = null;
  165. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
  166. request.Method = "Post";
  167. request.Accept = "*/*";
  168. request.Headers.Add("Accept-Language: zh-CN,zh;q=0.8");
  169. request.Headers.Add("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3");
  170. request.ContentType = "application/x-www-form-urlencoded";
  171. request.Timeout = 10000;
  172. request.Referer = strUrl;//.Remove(strUrl.LastIndexOf("/"));
  173. Console.WriteLine(strUrl);
  174. if (objCookieContainer == null)
  175. objCookieContainer = new CookieContainer();
  176. request.CookieContainer = objCookieContainer;
  177. //Console.WriteLine(objCookieContainer.ToString());
  178. if (!string.IsNullOrEmpty(strPost))
  179. {
  180. byte[] byteData = Encoding.UTF8.GetBytes(strPost.ToString().TrimEnd('&'));
  181. request.ContentLength = byteData.Length;
  182. using (Stream reqStream = request.GetRequestStream())
  183. {
  184. reqStream.Write(byteData, 0, byteData.Length);
  185. reqStream.Close();
  186. }
  187. }
  188. string strResponse = "";
  189. using (HttpWebResponse res = (HttpWebResponse)request.GetResponse())
  190. {
  191. objCookieContainer = request.CookieContainer;
  192. //QueryRecordForm.LoginCookie = objCookieContainer.GetCookies(new Uri(strUrl));
  193. res.Cookies = objCookieContainer.GetCookies(new Uri(strUrl));
  194. foreach (Cookie c in res.Cookies)
  195. {
  196. }
  197. using (Stream resStream = res.GetResponseStream())
  198. {
  199. byte[] buffer = new byte[1024];
  200. int read;
  201. while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0)
  202. {
  203. strResponse += Encoding.UTF8.GetString(buffer, 0, read);
  204. }
  205. }
  206. res.Close();
  207. }
  208. return strResponse;
  209. }
  210. catch (Exception e)
  211. {
  212. }
  213. return null;
  214. }
  215. public static string sendMessageCookie(string strUrl, string strPost, CookieContainer cookieContainer)
  216. {
  217. try
  218. {
  219. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
  220. if (cookieContainer != null)
  221. {
  222. request.CookieContainer = cookieContainer;
  223. }
  224. request.Method = "Post";
  225. request.Accept = "*/*";
  226. request.Headers.Add("Accept-Language: zh-CN,zh;q=0.8");
  227. request.Headers.Add("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3");
  228. request.Headers.Add("Cache-Control: max-age=0");
  229. request.Accept = "text/xml,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  230. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
  231. request.Timeout = 10000;
  232. request.Referer = strUrl;//.Remove(strUrl.LastIndexOf("/"));
  233. if (!string.IsNullOrEmpty(strPost))
  234. {
  235. request.ContentType = "application/json; text/html; charset=UTF-8";
  236. byte[] byteData = Encoding.UTF8.GetBytes(strPost.ToString().TrimEnd('&'));
  237. request.ContentLength = byteData.Length;
  238. using (Stream reqStream = request.GetRequestStream())
  239. {
  240. reqStream.Write(byteData, 0, byteData.Length);
  241. reqStream.Close();
  242. }
  243. }
  244. string strResponse = "";
  245. using (HttpWebResponse res = (HttpWebResponse)request.GetResponse())
  246. {
  247. if (cookieContainer != null)
  248. {
  249. cookieContainer = request.CookieContainer;
  250. }
  251. using (Stream resStream = res.GetResponseStream())
  252. {
  253. byte[] buffer = new byte[1024];
  254. int read;
  255. while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0)
  256. {
  257. strResponse += Encoding.UTF8.GetString(buffer, 0, read);
  258. }
  259. }
  260. res.Close();
  261. }
  262. return strResponse;
  263. }
  264. catch (Exception e)
  265. {
  266. //Console.WriteLine(e.ToString());
  267. }
  268. return null;
  269. }
  270. }
  271. class PostDateClass
  272. {
  273. String prop;
  274. public String Prop
  275. {
  276. get { return prop; }
  277. set { prop = value; }
  278. }
  279. String value;
  280. public String Value
  281. {
  282. get { return this.value; }
  283. set { this.value = value; }
  284. }
  285. /// <summary>
  286. /// 0为字符串,1为文件
  287. /// </summary>
  288. int type;
  289. public int Type
  290. {
  291. get { return type; }
  292. set { type = value; }
  293. }
  294. public PostDateClass(String prop, String value, int type = 0)
  295. {
  296. this.prop = prop;
  297. this.value = value;
  298. this.type = type;
  299. }
  300. }
  301. }