POST方式提交数据,一种众所周知的方式:

html页面中使用form表单提交,接收方式,使用Request.Form[""]或Request.QueryString[""]来获取。

这里介绍另外一种POST方式和接收方式,就是将整个数据作为加入到数据流中提交和接收

接收方式:

Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, , (int)s.Length);
return Encoding.UTF8.GetString(b);

只需要从input Stream中读取byte数据,然后转为string,再解析即可。如果要回复响应消息只需要用:Response.Write()  输出即可(和普通的页面输出一样)。

主动POST发送方式:

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.Method = "post"; byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
webrequest.ContentLength = postdatabyte.Length;
Stream stream;
stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, , postdatabyte.Length);
stream.Close(); using (var httpWebResponse = webrequest.GetResponse())
using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
{ String ret = responseStream.ReadToEnd(); T result = XmlDeserialize<T>(ret); return result;
}

使用HttpClient对象发送

 public static  string   PostXmlResponse(string url, string xmlString)

        {
HttpContent httpContent = new StringContent(xmlString);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient(); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
return t.Result;
}
return string.Empty;
}

从代码中可以看出仅仅是将字符串转为byte[] 类型,并加入到请求流中,进行请求即可达到POST效果,该种POST方式与上边所提到的接收方式相互配合使用。

下面一种方式是以键值对的方式主动POST传输的。

     /// <summary>
/// 发起httpPost 请求,可以上传文件
/// </summary>
/// <param name="url">请求的地址</param>
/// <param name="files">文件</param>
/// <param name="input">表单数据</param>
/// <param name="endoding">编码</param>
/// <returns></returns>
public static string PostResponse(string url, UpLoadFile[] files, Dictionary<string, string> input, Encoding endoding)
{ string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
//request.Credentials = CredentialCache.DefaultCredentials;
request.Expect = ""; MemoryStream stream = new MemoryStream(); byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
byte[] enterER = Encoding.ASCII.GetBytes("\r\n");
////提交文件
if (files != null)
{
string fformat = "Content-Disposition:form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
foreach (UpLoadFile file in files)
{ stream.Write(line, , line.Length); //项目分隔符
string s = string.Format(fformat, file.Name, file.FileName, file.Content_Type);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, , data.Length);
stream.Write(file.Data, , file.Data.Length);
stream.Write(enterER, , enterER.Length); //添加\r\n
}
} //提交文本字段
if (input != null)
{
string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n"; //自带项目分隔符
foreach (string key in input.Keys)
{
string s = string.Format(format, key, input[key]);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, , data.Length);
} } byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //项目最后的分隔符字符串需要带上--
stream.Write(foot_data, , foot_data.Length); request.ContentLength = stream.Length;
Stream requestStream = request.GetRequestStream(); //写入请求数据
stream.Position = 0L;
stream.CopyTo(requestStream); //
stream.Close(); requestStream.Close(); try
{ HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse(); try
{
using (var responseStream = response.GetResponseStream())
using (var mstream = new MemoryStream())
{
responseStream.CopyTo(mstream);
string message = endoding.GetString(mstream.ToArray());
return message;
}
}
catch (Exception ex)
{
throw ex;
}
}
catch (WebException ex)
{
//response = (HttpWebResponse)ex.Response; //if (response.StatusCode == HttpStatusCode.BadRequest)
//{
// using (Stream data = response.GetResponseStream())
// {
// using (StreamReader reader = new StreamReader(data))
// {
// string text = reader.ReadToEnd();
// Console.WriteLine(text);
// }
// }
//} throw ex;
} }
catch (Exception ex)
{
throw ex;
}
}

通过两种主动POST提交 的代码可以看出,其主要区别在于发送前的数据格式 ContentType 的值。

下面列举几种常用的ContentType 值,并简述他们的区别

Content-Type 被指定为 application/x-www-form-urlencoded 时候,传输的数据格式需要如  title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3 所示格式,才能正确解析

Content-Type 被指定为 multipart/form-data 时候,所需格式如下面代码块中所示

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA

------WebKitFormBoundaryrGKCBY7qhFd3TrwA

Content-Disposition: form-data; name="text"

title

------WebKitFormBoundaryrGKCBY7qhFd3TrwA

Content-Disposition: form-data; name="file"; filename="chrome.png"

Content-Type: image/png

PNG ... content of chrome.png ...

------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

Content-Type 也可以被指定为 application/json ,最终传输格式为 {"title":"test","sub":[1,2,3]}  至于如何接收本人未经尝试,但是可以肯定的讲使用文章开头所说的接收方式接收后转为string类型再

发序列化是可行的。

Content-Type指定为 text/xml  ,传输的数据格式为

<?xml version="1.0"?>
<methodCall>
<methodName>examples.getStateName</methodName>
<params>
<param>
<value><i4></i4></value>
</param>
</params>
</methodCall>

此种方式,本人亦未经尝试,接受方式可以参考上文中 application/json 的接收方式。

由于xml的格式传输数据,使用相对较少,相信很多同学亦不知道如何将字符串解析为对象,下文将提供一种转换方式,供参考

            XmlDocument doc = new XmlDocument();
doc.LoadXml(weixin);//读取xml字符串
XmlElement root = doc.DocumentElement; ExmlMsg xmlMsg = new ExmlMsg()
{
FromUserName = root.SelectSingleNode("FromUserName").InnerText,
ToUserName = root.SelectSingleNode("ToUserName").InnerText,
CreateTime = root.SelectSingleNode("CreateTime").InnerText,
MsgType = root.SelectSingleNode("MsgType").InnerText,
};
if (xmlMsg.MsgType.Trim().ToLower() == "text")
{
xmlMsg.Content = root.SelectSingleNode("Content").InnerText;
}
else if (xmlMsg.MsgType.Trim().ToLower() == "event")
{
xmlMsg.EventName = root.SelectSingleNode("Event").InnerText;
}
return xmlMsg;
        private class ExmlMsg
{
/// <summary>
/// 本公众账号
/// </summary>
public string ToUserName { get; set; }
/// <summary>
/// 用户账号
/// </summary>
public string FromUserName { get; set; }
/// <summary>
/// 发送时间戳
/// </summary>
public string CreateTime { get; set; }
/// <summary>
/// 发送的文本内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 消息的类型
/// </summary>
public string MsgType { get; set; }
/// <summary>
/// 事件名称
/// </summary>
public string EventName { get; set; } }

至此,相信一部分同学能有所得。由于本人水平一般,文中所述可能有纰漏之处,还请路过高手指出,同时也欢迎在评论区贴出更好的 发送和接受方式,供大家学习和交流。

本文有参考:https://imququ.com/post/four-ways-to-post-data-in-http.html  ,向原文作者致谢。

												

C#中POST数据和接收的几种方式(抛砖引玉)的更多相关文章

  1. [转]C#中POST数据和接收的几种方式

    POST方式提交数据,一种众所周知的方式: html页面中使用form表单提交,接收方式,使用Request.Form[""]或Request.QueryString[" ...

  2. C#中POST数据和接收的几种方式

    POST方式提交数据,一种众所周知的方式: html页面中使用form表单提交,接收方式,使用Request.Form[""]或Request.QueryString[" ...

  3. 【Java8新特性】面试官问我:Java8中创建Stream流有哪几种方式?

    写在前面 先说点题外话:不少读者工作几年后,仍然在使用Java7之前版本的方法,对于Java8版本的新特性,甚至是Java7的新特性几乎没有接触过.真心想对这些读者说:你真的需要了解下Java8甚至以 ...

  4. C# 中一些类关系的判定方法 C#中关于增强类功能的几种方式 Asp.Net Core 轻松学-多线程之取消令牌

    1.  IsAssignableFrom实例方法 判断一个类或者接口是否继承自另一个指定的类或者接口. public interface IAnimal { } public interface ID ...

  5. python中字典的循环遍历的两种方式

    开发中经常会用到对于字典.列表等数据的循环遍历,但是python中对于字典的遍历对于很多初学者来讲非常陌生,今天就来讲一下python中字典的循环遍历的两种方式. 注意: python2和python ...

  6. Velocity中加载vm文件的三种方式

    Velocity中加载vm文件的三种方式: a.  加载classpath目录下的vm文件 /** * 初始化Velocity引擎 * --VelocityEngine是单例模式,线程安全 * @th ...

  7. Android中H5和Native交互的两种方式

    Android中H5和Native交互的两种方式:http://www.jianshu.com/p/bcb5d8582d92 注意事项: 1.android给h5页面注入一个对象(WZApp),这个对 ...

  8. 第1节 IMPALA:10、基本查询语法;11、数据加载的4种方式

    9.3. 创建数据库表 创建student表 CREATE TABLE IF NOT EXISTS mydb1.student (name STRING, age INT, contact INT ) ...

  9. Action中取得request,session的四种方式

    Action中取得request,session的四种方式 在Struts2中,从Action中取得request,session的对象进行应用是开发中的必需步骤,那么如何从Action中取得这些对象 ...

随机推荐

  1. nginx 安全优化

    http://nginx.org/en/docs/http/ngx_http_access_module.html  官网 1.允许特定的ip访问,拒绝特定ip server { listen 80; ...

  2. OC中加载html5调用html方法和修改HTML5内容

    1.利用webView控件加载本地html5或者网络上html5 2.设置控制器为webView的代理,遵守协议 3.实现代理方法webViewDidFinishLoad: 4.在代理方法中进行操作H ...

  3. Intellij IDEA 一些不为人知的技巧

    Intellij IDEA 一些不为人知的技巧 2016/12/06 | 分类: 基础技术 | 0 条评论 | 标签: IntelliJ 分享到:38 原文出处: khotyn 今天又听了 Jetbr ...

  4. [No00008F]PLSQL自动登录,记住用户名密码&日常使用技巧

    配置启动时的登录用户名和密码 这是个有争议的功能,因为记住密码会给带来数据安全的问题. 但假如是开发用的库,密码甚至可以和用户名相同,每次输入密码实在没什么意义,可以考虑让PLSQL Develope ...

  5. [LeetCode] Shuffle an Array 数组洗牌

    Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] n ...

  6. [LeetCode] Excel Sheet Column Number 求Excel表列序号

    Related to question Excel Sheet Column Title Given a column title as appear in an Excel sheet, retur ...

  7. C#计算代码执行时间

    System.Diagnostics.Stopwatch watch = new Stopwatch();watch.Start(); //要计算的操作 DoSomeThing(); watch.St ...

  8. AngularJS Scope(作用域)

    1. AngularJS Scope(作用域) Scope(作用域) 是应用在 HTML (视图) 和 JavaScript (控制器)之间的纽带. Scope 是一个对象,有可用的方法和属性. Sc ...

  9. 移动端重要的几个CSS3属性设置

    去掉点击链接和文本框对象的半透明覆盖(iOS)或者虚框(Android) -webkit-tap-hightlight-color:rgba(0,0,0,0); 禁用长按页面时弹出菜单(iOS下有效) ...

  10. 关于List的ConcurrentModificationException

    对ArrayList的操作我们可以通过索引象来访问,也可以通过Iterator来访问,只要不对ArrayList结构上进行修改都不会造成ConcurrentModificationException, ...