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页面,对于后台怎么获取有点想不起来了. 今天便做了几个实验,提交订单到后台,来掩饰后台如何接受表单内容: 实验 一 ...
随机推荐
- 利用Spring Hibernate注解packagesToScan的简化自动扫描方式
转自:https://blog.csdn.net/wzygis/article/details/28256045
- HTML5+Spring-MVC实现上传图片本地保存
以下就是具体的代码: 1.在jsp页面中的代码: <span style="font-size:24px;"><form method="post&qu ...
- POJ 2353 DP
双向DP+记录路径. // by SiriusRen #include <stack> #include <cstdio> #include <cstring> u ...
- javascript动画函数封装
function animate(obj, target) { clearInterval(obj.timer); obj.timer = setInterval(function () { var ...
- SSH三个主流框架环境的搭建
part 1 Hibernate环境的搭建 part2 struts2环境的搭建 第一步:从struts2官网下载需要的各种资料和jar包 第二步:在ecplise里面创建web项目,然后在web ...
- 在IIS 10中注册自定义的IHttpModule
环境:Visual Studio 2015, IIS Express 10, ASP.NET 4.5 演示代码:http://files.cnblogs.com/files/joe-yang/Rewr ...
- 页面定制CSS代码初探(五):给每篇文章最后加上'<完>'
前言 我刚写博客的时候,有几篇是手动在最后加了个<完> 今天在看别人CSS布局时,发现很多::before和::after标签,因为没学过CSS,从名字看大概是前边/后边 加上某个东西的意 ...
- Unity3d 拖拽脚本报错 Can’t add script
报错截图: 报错原因: c#文件创建以后再改名,会报错找不到对应类. 类名和文件名要一致才行.(这个是Unity要求,c#本身不要求一致)
- 路飞学城Python-Day33
1.简述计算机操作系统中的“中断”的作用? 为什么有中断? 现代操作系统一般都是采用基于时间片的优先级调度算法,把CPU的时间划分为很细粒度的时间片,一个任务每次只能时间这么多的时间,时间到了就必须交 ...
- python matplotlib数据可视化
#基于python3 Matplotlib构建的3D图形: 使用pycharm的小伙伴把sciview给关掉: 因为sciview显示的是png图片.3d图形一般我们都需要拖拖拽拽的. 参见: htt ...