HttpWebRequest 表单提交
- /// <summary>
- /// http请求
- /// </summary>
- public static class ZkWebRequestHelp
- {
- /// <summary>
- /// 发送Htpp请求
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="url">请求的Url</param>
- /// <param name="headPara">头部集合键值对 默认为空</param>
- /// <param name="method">请求方法 默认get</param>
- /// <param name="para">参数字符 默认为字符串的空</param>
- /// <param name="contentType">请求的数据类型 </param>
- /// <param name="timeOut">超时时间 默认15s</param>
- /// <param name="encoding">编码方式 默认 Encoding.UTF8</param>
- /// <returns></returns>
- 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)
- {
- string str = SendRequestGetStr(url, method, headPara, para, userAgent, contentType, timeOut, encoding);
- if (needDeserialize)
- {
- return JsonConvert.DeserializeObject<T>(str);
- }
- return default(T);
- }
- /// <summary>
- /// 发送Htpp请求
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="url">请求的Url</param>
- /// <param name="headPara">头部集合键值对 默认为空</param>
- /// <param name="method">请求方法 默认get</param>
- /// <param name="para">参数字符 默认为字符串的空</param>
- /// <param name="contentType">请求的数据类型 </param>
- /// <param name="timeOut">超时时间 默认15s</param>
- /// <param name="encoding">编码方式 默认 Encoding.UTF8</param>
- /// <returns></returns>
- 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)
- {
- para = para ?? "";
- var request = (HttpWebRequest)WebRequest.Create(url);
- encoding = encoding ?? Encoding.UTF8;
- var dataByte = encoding.GetBytes(para);//请求参数
- request.Method = string.Compare(method, "get", StringComparison.OrdinalIgnoreCase) == ? WebRequestMethods.Http.Get : WebRequestMethods.Http.Post;
- request.Timeout = timeOut * ;
- request.AllowAutoRedirect = false;
- request.ContentLength = dataByte.Length;
- request.ContentType = contentType ?? "application/x-www-form-urlencoded";
- request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
- 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";
- if (headPara != null && headPara.Count > )
- {
- foreach (string key in headPara)
- {
- request.Headers.Add(key, headPara[key]);
- }
- }
- if (request.Method == WebRequestMethods.Http.Post)
- {
- var stream = request.GetRequestStream();
- stream.Write(dataByte, , dataByte.Length);
- stream.Close();
- }
- var response = (HttpWebResponse)request.GetResponse();
- var sr = new StreamReader(response.GetResponseStream());
- return sr.ReadToEnd();
- }
- public static byte[] DownloadByteArray(string url)
- {
- var request = (HttpWebRequest)WebRequest.Create(url);
- request.Timeout = * ;
- request.AllowAutoRedirect = false;
- request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
- request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
- request.Method = WebRequestMethods.Http.Get;
- var response = (HttpWebResponse)request.GetResponse();
- using (var responseSteam = response.GetResponseStream())
- {
- using (var ms = new MemoryStream())
- {
- responseSteam.CopyTo(ms);
- return ms.GetBuffer();
- }
- }
- }
- }
- public class SendFileHelper
- {
- readonly Encoding encoding = Encoding.UTF8;
- public string UploadData(string url, byte[] bytes)
- {
- var request = (HttpWebRequest)WebRequest.Create(url);
- request.Timeout = 10 * 1000;
- request.AllowAutoRedirect = false;
- request.ContentType = ContentType;
- request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
- request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
- request.Headers.Add("apptype", "2");
- request.Method = WebRequestMethods.Http.Post;
- if (request.Method == WebRequestMethods.Http.Post)
- {
- var stream = request.GetRequestStream();
- stream.Write(bytes, 0, bytes.Length);
- stream.Close();
- }
- var response = (HttpWebResponse)request.GetResponse();
- var sr = new StreamReader(response.GetResponseStream());
- return sr.ReadToEnd();
- }
- #region 组建尾部边界值
- /**/
- /// <summary>
- /// 拼接所有的二进制数组为一个数组
- /// </summary>
- /// <param name="byteArrays">数组</param>
- /// <returns></returns>
- /// <remarks>加上结束边界</remarks>
- public byte[] JoinBytes(ArrayList byteArrays)
- {
- int length = 0;
- int readLength = 0;
- // 加上结束边界
- string endBoundary = Boundary + "--\r\n"; //结束边界
- byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
- byteArrays.Add(endBoundaryBytes);
- foreach (byte[] b in byteArrays)
- {
- length += b.Length;
- }
- byte[] bytes = new byte[length];
- // 遍历复制
- //
- foreach (byte[] b in byteArrays)
- {
- b.CopyTo(bytes, readLength);
- readLength += b.Length;
- }
- return bytes;
- }
- #endregion
- #region 普通数据加入数组
- /**/
- /// <summary>
- /// 获取普通表单区域二进制数组
- /// </summary>
- /// <param name="fieldName">表单名</param>
- /// <param name="fieldValue">表单值</param>
- /// <returns></returns>
- /// <remarks>
- /// -----------------------------7d52ee27210a3c\r\nContent-Disposition: form-data; name=\"表单名\"\r\n\r\n表单值\r\n
- /// </remarks>
- public byte[] CreateFieldData(string fieldName, string fieldValue)
- {
- string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
- string text = String.Format(textTemplate, fieldName, fieldValue);
- byte[] bytes = encoding.GetBytes(text);
- return bytes;
- }
- #endregion
- #region 文件加入数组
- /**/
- /// <summary>
- /// 获取文件上传表单区域二进制数组
- /// </summary>
- /// <param name="fieldName">表单名</param>
- /// <param name="filename">文件名</param>
- /// <param name="contentType">文件类型</param>
- /// <param name="contentLength">文件长度</param>
- /// <param name="stream">文件流</param>
- /// <returns>二进制数组</returns>
- public byte[] CreateFieldData(string fieldName, string filename, byte[] fileBytes, string contentType = "application/octet-stream")
- {
- string end = "\r\n";
- string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
- // 头数据
- string data = String.Format(textTemplate, fieldName, filename, contentType);
- byte[] bytes = encoding.GetBytes(data);
- // 尾数据
- byte[] endBytes = encoding.GetBytes(end);
- // 合成后的数组
- byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];
- bytes.CopyTo(fieldData, 0); // 头数据
- fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据
- endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); // \r\n
- return fieldData;
- }
- #endregion
- #region 属性
- public string Boundary
- {
- get
- {
- string[] bArray, ctArray;
- string contentType = ContentType;
- ctArray = contentType.Split(';');
- if (ctArray[0].Trim().ToLower() == "multipart/form-data")
- {
- bArray = ctArray[1].Split('=');
- return "--" + bArray[1];
- }
- return null;
- }
- }
- public string ContentType
- {
- get
- {
- return "multipart/form-data; boundary=---------------------------7d5b915500cee";
- }
- }
- #endregion
- }
使用示例(表单提交):
- var byteArray = ZkWebRequestHelp.DownloadByteArray("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png");//获取文件流
- var sendFile = new SendFileHelper();
- ArrayList bytesArray = new ArrayList();
- // 普通表单
- bytesArray.Add(sendFile.CreateFieldData("name", "张三"));//普通数据
- bytesArray.Add(sendFile.CreateFieldData("age", "18"));//普通数据
- bytesArray.Add(sendFile.CreateFieldData("file", "123.jpg", byteArray));//文件上传
- var bytes = sendFile.JoinBytes(bytesArray);
- sendFile.UploadData("http://localhost:16311/api/Authorization/UploadData", bytes);
HttpWebRequest 表单提交的更多相关文章
- 利用HttpWebRequest模拟表单提交
using System; using System.Collections.Specialized; using System.IO; using System.Net; using System. ...
- 利用HttpWebRequest模拟表单提交 JQuery 的一个轻量级 Guid 字符串拓展插件. 轻量级Config文件AppSettings节点编辑帮助类
利用HttpWebRequest模拟表单提交 1 using System; 2 using System.Collections.Specialized; 3 using System.IO; ...
- form表单提交过程
本文为转载文章! 今天,我将站在HTML和单纯的Asp.net框架的角度来解释它们的工作方式,因此,本文不演示WebForms服务器控件的相关内容. 简单的表单,简单的处理方式 好了,让我们进入今天的 ...
- c# 模拟表单提交,post form 上传文件、大数据内容
表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,这个参数是由应用程序自行产生,它会用来识别每 ...
- c# 模拟表单提交,post form 上传文件、数据内容
转自:https://www.cnblogs.com/DoNetCShap/p/10696277.html 表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipar ...
- from表单提交数据之后,后台对象接受不到值
如果SSH框架下,前段页面通过from表单提交数据之后,在后台对象显示空值,也就是接收不到值得情况下.首先保证前段输入框有值,这个可以在提交的时候用jQuery的id或者name选择器alert弹出测 ...
- 不使用Ajax,如何实现表单提交不刷新页面
不使用Ajax,如何实现表单提交不刷新页面? 目前,我想到的是使用<iframe>,如果有其他的方式,后续再补. 举个栗子: 在表单上传文件的时候必须设置enctype="mul ...
- golang-web框架revel一个表单提交的总结
这里要介绍好是revel框架的表单post提交的列子,主要是用于入门学习,和一些知识点的讲解: 首先: 来了解一个问题那就是重复提交表单,做过form表单提交的同学都知道,如果表单提交后不做处理,那么 ...
- 关于我们经常用到的form表单提交
工作中遇到了太多太多的表单提交问题,曾经学过一个HTML的表单提交给 另外一个HTML页面,对于后台怎么获取有点想不起来了. 今天便做了几个实验,提交订单到后台,来掩饰后台如何接受表单内容: 实验 一 ...
随机推荐
- php的异步并行扩展swoole
Swoole是PHP的异步并行扩展,有点像Node.js,但swoole既支持同步又支持异步,比node更强大.Swoole扩展是基于epoll高性能事件轮询,并且是多线程的,性能非常好. Swool ...
- 剑指offer——04重建二叉树(Python3)
思路:在数据结构中,有一个条件反射,谈及二叉树,就递归.所以在实现重建二叉树时,也应该用到递归的思想. 在前序遍历中,根节点处于第一个:在中序遍历中,根节点的左边为左子树节点,根节点右边为右子树节点. ...
- ios 中生成随机数
ios 有如下三种随机数方法: 1. srand((unsigned)time(0)); //不加这句每次产生的随机数不变 int i = rand() % 5; 2. s ...
- python网络编程三次握手和四次挥手
TCP是因特网中的传输层协议,使用三次握手协议建立连接.当主动方发出SYN连接请求后,等待对方回答SYN+ACK[1],并最终对对方的 SYN 执行 ACK 确认.这种建立连接的方法可以防止产生错误的 ...
- Android设计模式——单例模式
1.单例模式就是确保一个类,只有一个实例化对象,而且自行实例化并向整个系统提供这个实例. 2.使用场景: 确保某个类,有且只有一个对象,避免产生对个对象,消耗过多的资源. 2.实现单例模式的重要点: ...
- PHP的反射API
PHP5的类和对象并没有告诉我们类内的所有一切,而只是报告了他们的公共成员.要充分了解一个类,需要知道其私有 成员和保护成员,还要知道其方法所期望的参数,对此我们要使用API 1.获得反射API的转储 ...
- JS怎样计算过关分数
一个游戏,前20关是每一关自身的分数,//21-30关每一关是10分//31-40关,每一关是20分//41-49关,每一关是30分//50关,是100分 <!DOCTYPE html> ...
- DOS下格式化移动硬盘
有的时候移动硬盘出现问题,在Win下没法操作,只能到dos下格式化.以下是用Win自带的diskpart完成格式化. 1 win + r -> cmd 进入dos 2 diskpart ...
- zabbix、agent端服务器图形化展示
[root@agent ~]# cat /etc/hostname agent.zabbix.com [root@agent ~]# cat /etc/hosts 127.0.0.1 localh ...
- (翻译) Inheritance and the prototype chain 继承和原型链
JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++) ...