使用HttpWebRequest发送自定义POST请求
2013-06-03 13:50
567 查看
平时用浏览器看网页的时候,点击一下submit按钮的时候其实就是给服务器发送了一个POST请求。但是如何在自己的C#程序里面实现类似的功能呢?本文给出了一个简单的范例,可以实现类似的和web server之间的POST通讯。通过程序发送POST的过程如下所示:
WebRequest是获得一些列应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。所以我们的程序里面有一个对返回对象的类型进行测试的过程。
范例代码下载
1. 创建httpWebRequest对象
HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得。WebRequest是获得一些列应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。所以我们的程序里面有一个对返回对象的类型进行测试的过程。
2. 初始化HttpWebRequest对象
这个过程提供一些http请求常用的属性:agentstring,contenttype等其中agentstring比较有意思,它是用来识别你用的浏览器名字的,通过设置这个属性你可以欺骗服务器你是一个IE,firefox甚至是mac里面的safari。很多认真设计的网站都会根据这个值来返回对用户浏览器特别优化过的代码。3. 附加要POST给服务器的数据到HttpWebRequest对象
附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。4. 读取服务器的返回信息
读取服务器返回的时候,要注意返回数据的encoding。如果我们提供的解码类型不对会造成乱码。比较常见的是utf-8和gb2312之间的混淆,据我测试,国内的主机一般都是gb2312编码的。一般设计良好的网站会把它编码的方式放在返回的http header里面,但是也有不少网站根本没有,我们只能通过一个对返回二进制值的统计方法来确定它的编码方式。using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace SimpleWebRequest { class Program { static void Main(string[] args) { Console.WriteLine( PostDataToUrl("test", "http://www.microsoft.com") ); } ///<summary> /// Post data到url ///</summary> ///<param name="data">要post的数据</param> ///<param name="url">目标url</param> ///<returns>服务器响应</returns> static string PostDataToUrl(string data, string url) { Encoding encoding = Encoding.GetEncoding(sRequestEncoding); byte[] bytesToPost = encoding.GetBytes(data); return PostDataToUrl(bytesToPost, url); } ///<summary> /// Post data到url ///</summary> ///<param name="data">要post的数据</param> ///<param name="url">目标url</param> ///<returns>服务器响应</returns> static string PostDataToUrl(byte[] data, string url) { #region 创建httpWebRequest对象 WebRequest webRequest = WebRequest.Create(url); HttpWebRequest httpRequest = webRequest as HttpWebRequest;//as用于类型转换 if (httpRequest == null) { throw new ApplicationException( string.Format("Invalid url string: {0}", url) ); } #endregion #region 填充httpWebRequest的基本信息 httpRequest.UserAgent = sUserAgent; httpRequest.ContentType = sContentType; httpRequest.Method = "POST"; #endregion #region 填充要post的内容 httpRequest.ContentLength = data.Length; Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); #endregion #region 发送post请求到服务器并读取服务器返回信息 Stream responseStream; try { responseStream = httpRequest.GetResponse().GetResponseStream(); } catch(Exception e) { // log error Console.WriteLine( string.Format("POST操作发生异常:{0}", e.Message) ); throw e; } #endregion #region 读取服务器返回信息 string stringResponse = string.Empty; using(StreamReader responseReader = new StreamReader(responseStream, Encoding.GetEncoding(sResponseEncoding))) { stringResponse = responseReader.ReadToEnd(); } responseStream.Close(); #endregion return stringResponse; } const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; const string sContentType = "application/x-www-form-urlencoded"; const string sRequestEncoding = "ascii"; const string sResponseEncoding = "gb2312"; } }
范例代码下载
相关文章推荐
- 使用HttpWebRequest发送自定义POST请求
- 使用HttpWebRequest发送自定义POST请求
- 使用HttpWebRequest发送自定义POST请求
- 使用HttpWebRequest发送自定义POST请求(以http方式推送消息)
- 使用HttpWebRequest发送自定义POST请求
- 使用HttpWebRequest发送自定义POST请求
- 使用HttpWebRequest发送自定义POST请求(转帖)
- 使用HttpWebRequest发送自定义POST请求
- 使用 HttpWebRequest 发送模拟 POST 请求
- C# 后台使用HttpWebRequest发送POST请求帮助类
- 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端
- 通过HttpWebRequest 发送 POST 请求实现自动登陆
- 使用JavaScript的XMLHttpRequest发送POST、GET请求以及接收返回值
- js_html_input中autocomplete="off"在chrom中失效的解决办法 使用JS模拟锚点跳转 js如何获取url参数 C#模拟httpwebrequest请求_向服务器模拟cookie发送 实习期学到的技术(一) LinqPad的变量比较功能 ASP.NET EF 使用LinqPad 快速学习Linq
- C#实现通过HttpWebRequest发送POST请求实现网站自动登陆
- (微信API接口开发) 使用HttpWebRequest进行请求时发生错误:基础连接已关闭,发送时发生错误处理
- 通过HttpWebRequest 发送 POST 请求实现自动登陆
- 通过HttpWebRequest 发送 POST 请求实现自动登陆
- C#实现通过HttpWebRequest发送POST请求实现网站自动登陆