1. /// <summary>
  2. /// http请求
  3. /// </summary>
  4. public static class ZkWebRequestHelp
  5. {
  6.  
  7. /// <summary>
  8. /// 发送Htpp请求
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. /// <param name="url">请求的Url</param>
  12. /// <param name="headPara">头部集合键值对 默认为空</param>
  13. /// <param name="method">请求方法 默认get</param>
  14. /// <param name="para">参数字符 默认为字符串的空</param>
  15. /// <param name="contentType">请求的数据类型 </param>
  16. /// <param name="timeOut">超时时间 默认15s</param>
  17. /// <param name="encoding">编码方式 默认 Encoding.UTF8</param>
  18. /// <returns></returns>
  19. public static T SendRequest<T>(string url, string method = "get", NameValueCollection headPara = null, string para = null, string userAgent = null, string contentType = null, int timeOut = , Encoding encoding = null, bool needDeserialize = true)
  20. {
  21. string str = SendRequestGetStr(url, method, headPara, para, userAgent, contentType, timeOut, encoding);
  22. if (needDeserialize)
  23. {
  24. return JsonConvert.DeserializeObject<T>(str);
  25. }
  26. return default(T);
  27. }
  28.  
  29. /// <summary>
  30. /// 发送Htpp请求
  31. /// </summary>
  32. /// <typeparam name="T"></typeparam>
  33. /// <param name="url">请求的Url</param>
  34. /// <param name="headPara">头部集合键值对 默认为空</param>
  35. /// <param name="method">请求方法 默认get</param>
  36. /// <param name="para">参数字符 默认为字符串的空</param>
  37. /// <param name="contentType">请求的数据类型 </param>
  38. /// <param name="timeOut">超时时间 默认15s</param>
  39. /// <param name="encoding">编码方式 默认 Encoding.UTF8</param>
  40. /// <returns></returns>
  41. public static string SendRequestGetStr(string url, string method = "get", NameValueCollection headPara = null, string para = null, string userAgent = null, string contentType = null, int timeOut = , Encoding encoding = null)
  42. {
  43. para = para ?? "";
  44. var request = (HttpWebRequest)WebRequest.Create(url);
  45. encoding = encoding ?? Encoding.UTF8;
  46. var dataByte = encoding.GetBytes(para);//请求参数
  47. request.Method = string.Compare(method, "get", StringComparison.OrdinalIgnoreCase) == ? WebRequestMethods.Http.Get : WebRequestMethods.Http.Post;
  48. request.Timeout = timeOut * ;
  49. request.AllowAutoRedirect = false;
  50. request.ContentLength = dataByte.Length;
  51. request.ContentType = contentType ?? "application/x-www-form-urlencoded";
  52. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  53. request.UserAgent = userAgent ?? "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
  54. if (headPara != null && headPara.Count > )
  55. {
  56. foreach (string key in headPara)
  57. {
  58. request.Headers.Add(key, headPara[key]);
  59. }
  60. }
  61. if (request.Method == WebRequestMethods.Http.Post)
  62. {
  63. var stream = request.GetRequestStream();
  64. stream.Write(dataByte, , dataByte.Length);
  65. stream.Close();
  66. }
  67.  
  68. var response = (HttpWebResponse)request.GetResponse();
  69. var sr = new StreamReader(response.GetResponseStream());
  70. return sr.ReadToEnd();
  71. }
  72.  
  73. public static byte[] DownloadByteArray(string url)
  74. {
  75. var request = (HttpWebRequest)WebRequest.Create(url);
  76. request.Timeout = * ;
  77. request.AllowAutoRedirect = false;
  78. request.ContentType = "application/x-www-form-urlencoded";
  79. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  80. request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
  81. request.Method = WebRequestMethods.Http.Get;
  82. var response = (HttpWebResponse)request.GetResponse();
  83. using (var responseSteam = response.GetResponseStream())
  84. {
  85. using (var ms = new MemoryStream())
  86. {
  87. responseSteam.CopyTo(ms);
  88. return ms.GetBuffer();
  89. }
  90. }
  91.  
  92. }
  93. }
  1. public class SendFileHelper
  2. {
  3. readonly Encoding encoding = Encoding.UTF8;
  4.  
  5. public string UploadData(string url, byte[] bytes)
  6. {
  7. var request = (HttpWebRequest)WebRequest.Create(url);
  8. request.Timeout = 10 * 1000;
  9. request.AllowAutoRedirect = false;
  10. request.ContentType = ContentType;
  11. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  12. request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
  13. request.Headers.Add("apptype", "2");
  14. request.Method = WebRequestMethods.Http.Post;
  15. if (request.Method == WebRequestMethods.Http.Post)
  16. {
  17. var stream = request.GetRequestStream();
  18. stream.Write(bytes, 0, bytes.Length);
  19. stream.Close();
  20. }
  21. var response = (HttpWebResponse)request.GetResponse();
  22. var sr = new StreamReader(response.GetResponseStream());
  23. return sr.ReadToEnd();
  24. }
  25.  
  26. #region 组建尾部边界值
  27. /**/
  28. /// <summary>
  29. /// 拼接所有的二进制数组为一个数组
  30. /// </summary>
  31. /// <param name="byteArrays">数组</param>
  32. /// <returns></returns>
  33. /// <remarks>加上结束边界</remarks>
  34. public byte[] JoinBytes(ArrayList byteArrays)
  35. {
  36. int length = 0;
  37. int readLength = 0;
  38.  
  39. // 加上结束边界
  40. string endBoundary = Boundary + "--\r\n"; //结束边界
  41. byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
  42. byteArrays.Add(endBoundaryBytes);
  43.  
  44. foreach (byte[] b in byteArrays)
  45. {
  46. length += b.Length;
  47. }
  48. byte[] bytes = new byte[length];
  49.  
  50. // 遍历复制
  51. //
  52. foreach (byte[] b in byteArrays)
  53. {
  54. b.CopyTo(bytes, readLength);
  55. readLength += b.Length;
  56. }
  57.  
  58. return bytes;
  59. }
  60. #endregion
  61.  
  62. #region 普通数据加入数组
  63. /**/
  64. /// <summary>
  65. /// 获取普通表单区域二进制数组
  66. /// </summary>
  67. /// <param name="fieldName">表单名</param>
  68. /// <param name="fieldValue">表单值</param>
  69. /// <returns></returns>
  70. /// <remarks>
  71. /// -----------------------------7d52ee27210a3c\r\nContent-Disposition: form-data; name=\"表单名\"\r\n\r\n表单值\r\n
  72. /// </remarks>
  73. public byte[] CreateFieldData(string fieldName, string fieldValue)
  74. {
  75. string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
  76. string text = String.Format(textTemplate, fieldName, fieldValue);
  77. byte[] bytes = encoding.GetBytes(text);
  78. return bytes;
  79. }
  80. #endregion
  81.  
  82. #region 文件加入数组
  83. /**/
  84. /// <summary>
  85. /// 获取文件上传表单区域二进制数组
  86. /// </summary>
  87. /// <param name="fieldName">表单名</param>
  88. /// <param name="filename">文件名</param>
  89. /// <param name="contentType">文件类型</param>
  90. /// <param name="contentLength">文件长度</param>
  91. /// <param name="stream">文件流</param>
  92. /// <returns>二进制数组</returns>
  93. public byte[] CreateFieldData(string fieldName, string filename, byte[] fileBytes, string contentType = "application/octet-stream")
  94. {
  95. string end = "\r\n";
  96. string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  97.  
  98. // 头数据
  99. string data = String.Format(textTemplate, fieldName, filename, contentType);
  100. byte[] bytes = encoding.GetBytes(data);
  101.  
  102. // 尾数据
  103. byte[] endBytes = encoding.GetBytes(end);
  104.  
  105. // 合成后的数组
  106. byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];
  107.  
  108. bytes.CopyTo(fieldData, 0); // 头数据
  109. fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据
  110. endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); // \r\n
  111.  
  112. return fieldData;
  113. }
  114. #endregion
  115.  
  116. #region 属性
  117. public string Boundary
  118. {
  119. get
  120. {
  121. string[] bArray, ctArray;
  122. string contentType = ContentType;
  123. ctArray = contentType.Split(';');
  124. if (ctArray[0].Trim().ToLower() == "multipart/form-data")
  125. {
  126. bArray = ctArray[1].Split('=');
  127. return "--" + bArray[1];
  128. }
  129. return null;
  130. }
  131. }
  132.  
  133. public string ContentType
  134. {
  135. get
  136. {
  137. return "multipart/form-data; boundary=---------------------------7d5b915500cee";
  138. }
  139. }
  140. #endregion
  141. }

  使用示例(表单提交):

  1. var byteArray = ZkWebRequestHelp.DownloadByteArray("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png");//获取文件流
  2. var sendFile = new SendFileHelper();
  3. ArrayList bytesArray = new ArrayList();
  4. // 普通表单
  5. bytesArray.Add(sendFile.CreateFieldData("name", "张三"));//普通数据
  6. bytesArray.Add(sendFile.CreateFieldData("age", "18"));//普通数据
  7. bytesArray.Add(sendFile.CreateFieldData("file", "123.jpg", byteArray));//文件上传
  8. var bytes = sendFile.JoinBytes(bytesArray);
  9. sendFile.UploadData("http://localhost:16311/api/Authorization/UploadData", bytes);

  

HttpWebRequest 表单提交的更多相关文章

  1. 利用HttpWebRequest模拟表单提交

    using System; using System.Collections.Specialized; using System.IO; using System.Net; using System. ...

  2. 利用HttpWebRequest模拟表单提交 JQuery 的一个轻量级 Guid 字符串拓展插件. 轻量级Config文件AppSettings节点编辑帮助类

    利用HttpWebRequest模拟表单提交   1 using System; 2 using System.Collections.Specialized; 3 using System.IO; ...

  3. form表单提交过程

    本文为转载文章! 今天,我将站在HTML和单纯的Asp.net框架的角度来解释它们的工作方式,因此,本文不演示WebForms服务器控件的相关内容. 简单的表单,简单的处理方式 好了,让我们进入今天的 ...

  4. c# 模拟表单提交,post form 上传文件、大数据内容

    表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,这个参数是由应用程序自行产生,它会用来识别每 ...

  5. c# 模拟表单提交,post form 上传文件、数据内容

    转自:https://www.cnblogs.com/DoNetCShap/p/10696277.html 表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipar ...

  6. from表单提交数据之后,后台对象接受不到值

    如果SSH框架下,前段页面通过from表单提交数据之后,在后台对象显示空值,也就是接收不到值得情况下.首先保证前段输入框有值,这个可以在提交的时候用jQuery的id或者name选择器alert弹出测 ...

  7. 不使用Ajax,如何实现表单提交不刷新页面

    不使用Ajax,如何实现表单提交不刷新页面? 目前,我想到的是使用<iframe>,如果有其他的方式,后续再补. 举个栗子: 在表单上传文件的时候必须设置enctype="mul ...

  8. golang-web框架revel一个表单提交的总结

    这里要介绍好是revel框架的表单post提交的列子,主要是用于入门学习,和一些知识点的讲解: 首先: 来了解一个问题那就是重复提交表单,做过form表单提交的同学都知道,如果表单提交后不做处理,那么 ...

  9. 关于我们经常用到的form表单提交

    工作中遇到了太多太多的表单提交问题,曾经学过一个HTML的表单提交给 另外一个HTML页面,对于后台怎么获取有点想不起来了. 今天便做了几个实验,提交订单到后台,来掩饰后台如何接受表单内容: 实验 一 ...

随机推荐

  1. php的异步并行扩展swoole

    Swoole是PHP的异步并行扩展,有点像Node.js,但swoole既支持同步又支持异步,比node更强大.Swoole扩展是基于epoll高性能事件轮询,并且是多线程的,性能非常好. Swool ...

  2. 剑指offer——04重建二叉树(Python3)

    思路:在数据结构中,有一个条件反射,谈及二叉树,就递归.所以在实现重建二叉树时,也应该用到递归的思想. 在前序遍历中,根节点处于第一个:在中序遍历中,根节点的左边为左子树节点,根节点右边为右子树节点. ...

  3. ios 中生成随机数

    ios 有如下三种随机数方法: 1.    srand((unsigned)time(0));  //不加这句每次产生的随机数不变        int i = rand() % 5; 2.    s ...

  4. python网络编程三次握手和四次挥手

    TCP是因特网中的传输层协议,使用三次握手协议建立连接.当主动方发出SYN连接请求后,等待对方回答SYN+ACK[1],并最终对对方的 SYN 执行 ACK 确认.这种建立连接的方法可以防止产生错误的 ...

  5. Android设计模式——单例模式

    1.单例模式就是确保一个类,只有一个实例化对象,而且自行实例化并向整个系统提供这个实例. 2.使用场景: 确保某个类,有且只有一个对象,避免产生对个对象,消耗过多的资源. 2.实现单例模式的重要点: ...

  6. PHP的反射API

    PHP5的类和对象并没有告诉我们类内的所有一切,而只是报告了他们的公共成员.要充分了解一个类,需要知道其私有 成员和保护成员,还要知道其方法所期望的参数,对此我们要使用API 1.获得反射API的转储 ...

  7. JS怎样计算过关分数

    一个游戏,前20关是每一关自身的分数,//21-30关每一关是10分//31-40关,每一关是20分//41-49关,每一关是30分//50关,是100分 <!DOCTYPE html> ...

  8. DOS下格式化移动硬盘

    有的时候移动硬盘出现问题,在Win下没法操作,只能到dos下格式化.以下是用Win自带的diskpart完成格式化. 1  win + r   -> cmd  进入dos 2  diskpart ...

  9. zabbix、agent端服务器图形化展示

    [root@agent ~]# cat /etc/hostname agent.zabbix.com [root@agent ~]# cat /etc/hosts 127.0.0.1   localh ...

  10. (翻译) Inheritance and the prototype chain 继承和原型链

    JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++) ...