HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。另外,你可能预计需要显式地调用一个“Send”方法,实际上不需要。接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。
这种技术展示了如何限制请求重定向(request redirections)的次数, 并且设置了一个超时限制。下面是HttpWebRequest的一些属性,这些属性对于轻量级的自动化测试程序是非常重要的。
l AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。
l CookieContainer:获取或设置与此请求关联的cookie。
l Credentials:获取或设置请求的身份验证信息。
l KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。
l MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。
l Proxy:获取或设置请求的代理信息。
l SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
l Timeout:获取或设置请求的超时值。
l UserAgent:获取或设置 User-agent HTTP 标头的值
C# HttpWebRequest提交数据方式其实就是GET和POST两种,那么具体的实现以及操作注意事项是什么呢?那么本文就向你详细介绍C# HttpWebRequest提交数据方式的这两种利器。
C# HttpWebRequest提交数据方式学习之前我们先来看看什么是HttpWebRequest,它是 .net 基类库中的一个类,在命名空间 System.Net 下面,用来使用户通过HTTP协议和服务器交互。
C# HttpWebRequest的作用:
HttpWebRequest对HTTP协议进行了完整的封装,对HTTP协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。
C# HttpWebRequest提交数据方式:
程序使用HTTP协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成,下面对这两种方式进行一下说明:
C# HttpWebRequest提交数据方式1. GET 方式。
GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 http://www.google.com/webhp?hl=zh-CN 中,前面部分 http://www.google.com/webhp 表示数据提交的网址,后面部分 hl=zh-CN 表示附加的参数,其中 hl 表示一个键(key), zh-CN 表示这个键对应的值(value)。程序代码如下:
HttpWebRequest req =
(HttpWebRequest) HttpWebRequest.Create(
"http://www.google.com/webhp?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
C# HttpWebRequest提交数据方式2. POST 方式。
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。程序代码如下:
string param = "hl=zh-CN&newwindow=1"; //参数
byte[] bs = Encoding.ASCII.GetBytes(param); //参数转化为ascii码
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/intl/zh-CN/" ); //创建request
req.Method = "POST"; //确定传值的方式,此处为post方式传值
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
在上面的代码中,我们访问了 www.google.com 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。
C# HttpWebRequest提交数据方式3. 使用 GET 方式提交中文数据。
GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种,用 gb2312 方式编码访问的程序代码如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312"); //确定用哪种中文编码方式
string address = "http://www.baidu.com/s?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding); //拼接数据提交的网址和经过中文编码后的中文参数
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address); //创建request
req.Method = "GET"; //确定传值方式,此处为get方式
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
在上面的程序代码中,我们以 GET 方式访问了网址 http://www.baidu.com/s ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。常见的网站中, www.baidu.com (百度)的编码方式是 gb2312, www.google.com (谷歌)的编码方式是 utf8。
C# HttpWebRequest提交数据方式4. 使用 POST 方式提交中文数据。
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。用 gb2312 方式编码访问的程序代码如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312"); //确定中文编码方式。此处用gb2312
string param = HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("参数二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
byte[] postBytes = Encoding.ASCII.GetBytes(param); //将参数转化为assic码
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.baidu.com/s" );
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
req.ContentLength = postBytes.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。
以上列出了客户端程序使用HTTP协议与服务器交互的情况,常用的是 GET 和 POST 方式。现在流行的 WebService 也是通过 HTTP 协议来交互的,使用的是 POST 方法。与以上稍有所不同的是, WebService 提交的数据内容和接收到的数据内容都是使用了 XML 方式编码。所以, HttpWebRequest 也可以使用在调用 WebService 的情况下。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #region 公共方法 2 /// <summary> 3 /// Get数据接口 4 /// </summary> 5 /// <param name="getUrl">接口地址</param> 6 /// <returns></returns> 7 private static string GetWebRequest(string getUrl) 8 { 9 string responseContent = ""; 10 11 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl); 12 request.ContentType = "application/json"; 13 request.Method = "GET"; 14 15 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 16 //在这里对接收到的页面内容进行处理 17 using (Stream resStream = response.GetResponseStream()) 18 { 19 using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8)) 20 { 21 responseContent = reader.ReadToEnd().ToString(); 22 } 23 } 24 return responseContent; 25 } 26 /// <summary> 27 /// Post数据接口 28 /// </summary> 29 /// <param name="postUrl">接口地址</param> 30 /// <param name="paramData">提交json数据</param> 31 /// <param name="dataEncode">编码方式(Encoding.UTF8)</param> 32 /// <returns></returns> 33 private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode) 34 { 35 string responseContent = string.Empty; 36 try 37 { 38 byte[] byteArray = dataEncode.GetBytes(paramData); //转化 39 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); 40 webReq.Method = "POST"; 41 webReq.ContentType = "application/x-www-form-urlencoded"; 42 webReq.ContentLength = byteArray.Length; 43 using (Stream reqStream = webReq.GetRequestStream()) 44 { 45 reqStream.Write(byteArray, 0, byteArray.Length);//写入参数 46 //reqStream.Close(); 47 } 48 using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse()) 49 { 50 //在这里对接收到的页面内容进行处理 51 using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default)) 52 { 53 responseContent = sr.ReadToEnd().ToString(); 54 } 55 } 56 } 57 catch (Exception ex) 58 { 59 return ex.Message; 60 } 61 return responseContent; 62 } 63 64 #endregion
post支持cookie
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /// <summary> 2 /// 发起Post请求(采用HttpWebRequest,支持传Cookie) 3 /// </summary> 4 /// <param name="strUrl">请求Url</param> 5 /// <param name="formData">发送的表单数据</param> 6 /// <param name="strResult">返回请求结果(如果请求失败,返回异常消息)</param> 7 /// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> 8 /// <returns>返回:是否请求成功</returns> 9 public static bool HttpPost(string strUrl, Dictionary<string, string> formData, CookieContainer cookieContainer, out string strResult) 10 { 11 string strPostData = null; 12 if (formData != null && formData.Count > 0) 13 { 14 StringBuilder sbData = new StringBuilder(); 15 int i = 0; 16 foreach (KeyValuePair<string, string> data in formData) 17 { 18 if (i > 0) 19 { 20 sbData.Append("&"); 21 } 22 sbData.AppendFormat("{0}={1}", data.Key, data.Value); 23 i++; 24 } 25 strPostData = sbData.ToString(); 26 } 27 28 byte[] postBytes = string.IsNullOrEmpty(strPostData) ? new byte[0] : Encoding.UTF8.GetBytes(strPostData); 29 30 return HttpPost(strUrl, postBytes, cookieContainer, out strResult); 31 }
post上传文件
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /// <summary> 2 /// 发起Post文件请求(采用HttpWebRequest,支持传Cookie) 3 /// </summary> 4 /// <param name="strUrl">请求Url</param> 5 /// <param name="strFilePostName">上传文件的PostName</param> 6 /// <param name="strFilePath">上传文件路径</param> 7 /// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> 8 /// <param name="strResult">返回请求结果(如果请求失败,返回异常消息)</param> 9 /// <returns>返回:是否请求成功</returns> 10 public static bool HttpPostFile(string strUrl, string strFilePostName, string strFilePath, CookieContainer cookieContainer, out string strResult) 11 { 12 HttpWebRequest request = null; 13 FileStream fileStream = FileHelper.GetFileStream(strFilePath); 14 15 try 16 { 17 if (fileStream == null) 18 { 19 throw new FileNotFoundException(); 20 } 21 22 request = (HttpWebRequest)WebRequest.Create(strUrl); 23 request.Method = "POST"; 24 request.KeepAlive = false; 25 request.Timeout = 30000; 26 27 if (cookieContainer != null) 28 { 29 request.CookieContainer = cookieContainer; 30 } 31 32 string boundary = string.Format("---------------------------{0}", DateTime.Now.Ticks.ToString("x")); 33 34 byte[] header = Encoding.UTF8.GetBytes(string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n", 35 boundary, strFilePostName, Path.GetFileName(strFilePath))); 36 byte[] footer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary)); 37 38 request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); 39 request.ContentLength = header.Length + fileStream.Length + footer.Length; 40 41 using (Stream reqStream = request.GetRequestStream()) 42 { 43 // 写入分割线及数据信息 44 reqStream.Write(header, 0, header.Length); 45 46 // 写入文件 47 FileHelper.WriteFile(reqStream, fileStream); 48 49 // 写入尾部 50 reqStream.Write(footer, 0, footer.Length); 51 } 52 53 strResult = GetResponseResult(request, cookieContainer); 54 } 55 catch (Exception ex) 56 { 57 strResult = ex.Message; 58 return false; 59 } 60 finally 61 { 62 if (request != null) 63 { 64 request.Abort(); 65 } 66 if (fileStream != null) 67 { 68 fileStream.Close(); 69 } 70 } 71 72 return true; 73 } 74 75 76 /// <summary> 77 /// 获取请求结果字符串 78 /// </summary> 79 /// <param name="request">请求对象(发起请求之后)</param> 80 /// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> 81 /// <returns>返回请求结果字符串</returns> 82 private static string GetResponseResult(HttpWebRequest request, CookieContainer cookieContainer = null) 83 { 84 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 85 { 86 if (cookieContainer != null) 87 { 88 response.Cookies = cookieContainer.GetCookies(response.ResponseUri); 89 } 90 using (Stream rspStream = response.GetResponseStream()) 91 { 92 using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8)) 93 { 94 return reader.ReadToEnd(); 95 } 96 } 97