1、HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。
2、命名空间:System.Net
3、HttpWebRequest对象不是利用new关键字创建的(通过构造函数)。 而是利用Create()方法创建的。
4、你可能预计需要显示地调用一个“Send”方法,实际上不需要。
5、调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象
6、你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。

下面是HttpWebRequest的一些属性,这些属性对于轻量级的自动化测试程序是非常重要的。
a) AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。
b)CookieContainer:获取或设置与此请求关联的cookie。
c)Credentials:获取或设置请求的身份验证信息。
d)KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。
e)MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。
f) Proxy:获取或设置请求的代理信息。
g)SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
h)Timeout:获取或设置请求的超时值。
i) UserAgent:获取或设置 User-agent HTTP 标头的值

C# HttpWebRequest提交数据方式其实就是GET和POST两种

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)。程序代码如下:

  1. HttpWebRequest req =
  2. (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/webhp?hl=zh-CN" );
  3. req.Method = "GET";
  4. using (WebResponse wr = req.GetResponse())
  5. {
  6. //在这里对接收到的页面内容进行处理
  7. }

2. POST 方式。
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。程序代码如下:

  1. string param = "hl=zh-CN&newwindow=1"; //参数
  2. byte[] bs = Encoding.ASCII.GetBytes(param); //参数转化为ascii码
  3. HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://www.google.com/intl/zh-CN/" ); //创建request
  4. req.Method = "POST"; //确定传值的方式,此处为post方式传值
  5. req.ContentType = "application/x-www-form-urlencoded";
  6. req.ContentLength = bs.Length;
  7. using (Stream reqStream = req.GetRequestStream())
  8. {
  9. reqStream.Write(bs, , bs.Length);
  10. }
  11. using (WebResponse wr = req.GetResponse())
  12. {
  13. //在这里对接收到的页面内容进行处理
  14. }

3. 使用 GET 方式提交中文数据。
GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种,用 gb2312 方式编码访问的程序代码如下:

  1. Encoding myEncoding = Encoding.GetEncoding("gb2312"); //确定用哪种中文编码方式
  2. string address = "http://www.baidu.com/s?"+ HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding); //拼接数据提交的网址和经过中文编码后的中文参数
  3. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address); //创建request
  4. req.Method = "GET"; //确定传值方式,此处为get方式
  5. using (WebResponse wr = req.GetResponse())
  6. {
  7. //在这里对接收到的页面内容进行处理
  8. }

在上面的程序代码中,我们以 GET 方式访问了网址 http://www.baidu.com/s ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。常见的网站中, www.baidu.com (百度)的编码方式是 gb2312, www.google.com (谷歌)的编码方式是 utf8。

4. 使用 POST 方式提交中文数据。
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。用 gb2312 方式编码访问的程序代码如下:

  1. Encoding myEncoding = Encoding.GetEncoding("gb2312"); //确定中文编码方式。此处用gb2312
  2. string param = HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("参数二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
  3. byte[] postBytes = Encoding.ASCII.GetBytes(param); //将参数转化为assic码
  4. HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.baidu.com/s" );
  5. req.Method = "POST";
  6. req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
  7. req.ContentLength = postBytes.Length;
  8. using (Stream reqStream = req.GetRequestStream())
  9. {
  10. reqStream.Write(bs, , bs.Length);
  11. }
  12. using (WebResponse wr = req.GetResponse())
  13. {
  14. //在这里对接收到的页面内容进行处理
  15. }

从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。
以上列出了客户端程序使用HTTP协议与服务器交互的情况,常用的是 GET 和 POST 方式。

现在流行的 WebService 也是通过 HTTP 协议来交互的,使用的是 POST 方法。与以上稍有所不同的是, WebService 提交的数据内容和接收到的数据内容都是使用了 XML 方式编码。所以, HttpWebRequest 也可以使用在调用 WebService 的情况下。

C# HttpWebRequest提交数据方式的基本内容就向你介绍到这里,希望对你了解和学习C# HttpWebRequest提交数据方式有所帮助。

  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, , 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

OAuth头部

  1. //构造OAuth头部
  2. StringBuilder oauthHeader = new StringBuilder();
  3. oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey);
  4. oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce);
  5. oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp);
  6. oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1");
  7. oauthHeader.AppendFormat("oauth_version={0}, ", "1.0");
  8. oauthHeader.AppendFormat("oauth_signature={0}, ", sig);
  9. oauthHeader.AppendFormat("oauth_token={0}", accessToken);
  10.  
  11. //构造请求
  12. StringBuilder requestBody = new StringBuilder("");
  13. Encoding encoding = Encoding.GetEncoding("utf-8");
  14. byte[] data = encoding.GetBytes(requestBody.ToString());
  15.  
  16. // Http Request的设置
  17. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  18. request.Headers.Set("Authorization", oauthHeader.ToString());
  19. //request.Headers.Add("Authorization", authorization);
  20. request.ContentType = "application/atom+xml";
  21. request.Method = "GET";

C#通过WebClient/HttpWebRequest实现http的post/get方法
1.POST方法(httpWebRequest)

  1. //body是要传递的参数,格式"roleId=1&uid=2"
  2. //post的cotentType填写:"application/x-www-form-urlencoded"
  3. //soap填写:"text/xml; charset=utf-8"
  4. public static string PostHttp(string url, string body, string contentType)
  5. {
  6. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  7.  
  8. httpWebRequest.ContentType = contentType;
  9. httpWebRequest.Method = "POST";
  10. httpWebRequest.Timeout = ;
  11.  
  12. byte[] btBodys = Encoding.UTF8.GetBytes(body);
  13. httpWebRequest.ContentLength = btBodys.Length;
  14. httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length);
  15.  
  16. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  17. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
  18. string responseContent = streamReader.ReadToEnd();
  19.  
  20. httpWebResponse.Close();
  21. streamReader.Close();
  22. httpWebRequest.Abort();
  23. httpWebResponse.Close();
  24.  
  25. return responseContent;
  26. }

2.POST方法(WebClient)

  1. /// <summary>
  2. /// 通过WebClient类Post数据到远程地址,需要Basic认证;
  3. /// 调用端自己处理异常
  4. /// </summary>
  5. /// <param name="uri"></param>
  6. /// <param name="paramStr">name=张三&age=20</param>
  7. /// <param name="encoding">请先确认目标网页的编码方式</param>
  8. /// <param name="username"></param>
  9. /// <param name="password"></param>
  10. /// <returns></returns>
  11. public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
  12. {
  13. if (encoding == null)
  14. encoding = Encoding.UTF8;
  15.  
  16. string result = string.Empty;
  17.  
  18. WebClient wc = new WebClient();
  19.  
  20. // 采取POST方式必须加的Header
  21. wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  22.  
  23. byte[] postData = encoding.GetBytes(paramStr);
  24.  
  25. if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
  26. {
  27. wc.Credentials = GetCredentialCache(uri, username, password);
  28. wc.Headers.Add("Authorization", GetAuthorization(username, password));
  29. }
  30.  
  31. byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
  32. return encoding.GetString(responseData);// 解码
  33. }

3.Get方法(httpWebRequest)

  1. public static string GetHttp(string url, HttpContext httpContext)
  2. {
  3. string queryString = "?";
  4.  
  5. foreach (string key in httpContext.Request.QueryString.AllKeys)
  6. {
  7. queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
  8. }
  9.  
  10. queryString = queryString.Substring(, queryString.Length - );
  11.  
  12. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
  13.  
  14. httpWebRequest.ContentType = "application/json";
  15. httpWebRequest.Method = "GET";
  16. httpWebRequest.Timeout = ;
  17.  
  18. //byte[] btBodys = Encoding.UTF8.GetBytes(body);
  19. //httpWebRequest.ContentLength = btBodys.Length;
  20. //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
  21.  
  22. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  23. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
  24. string responseContent = streamReader.ReadToEnd();
  25.  
  26. httpWebResponse.Close();
  27. streamReader.Close();
  28.  
  29. return responseContent;
  30. }

4.basic验证的WebRequest/WebResponse

  1. /// <summary>
  2. /// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
  3. /// 调用端自己处理异常
  4. /// </summary>
  5. /// <param name="uri"></param>
  6. /// <param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>
  7. /// <param name="encoding">如果不知道具体的编码,传入null</param>
  8. /// <param name="username"></param>
  9. /// <param name="password"></param>
  10. /// <returns></returns>
  11. public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
  12. {
  13. string result = string.Empty;
  14.  
  15. WebRequest request = WebRequest.Create(new Uri(uri));
  16.  
  17. if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
  18. {
  19. request.Credentials = GetCredentialCache(uri, username, password);
  20. request.Headers.Add("Authorization", GetAuthorization(username, password));
  21. }
  22.  
  23. if (timeout > )
  24. request.Timeout = timeout;
  25.  
  26. WebResponse response = request.GetResponse();
  27. Stream stream = response.GetResponseStream();
  28. StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
  29.  
  30. result = sr.ReadToEnd();
  31.  
  32. sr.Close();
  33. stream.Close();
  34.  
  35. return result;
  36. }
  37.  
  38. #region # 生成 Http Basic 访问凭证 #
  39.  
  40. private static CredentialCache GetCredentialCache(string uri, string username, string password)
  41. {
  42. string authorization = string.Format("{0}:{1}", username, password);
  43.  
  44. CredentialCache credCache = new CredentialCache();
  45. credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
  46.  
  47. return credCache;
  48. }
  49.  
  50. private static string GetAuthorization(string username, string password)
  51. {
  52. string authorization = string.Format("{0}:{1}", username, password);
  53.  
  54. return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
  55. }
  56.  
  57. #endregion

原文链接

原始链接

C#中HttpWebRequest的用法详解(转载)的更多相关文章

  1. 【转】C#中HttpWebRequest的用法详解

    本文实例讲述了C#中HttpWebRequest的用法.分享给大家供大家参考.具体如下: HttpWebRequest类主要利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来 ...

  2. C#中HttpWebRequest的用法详解

    原文链接:http://www.cnblogs.com/love201314/p/5029312.html 1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数 ...

  3. python中yield的用法详解-转载

    原文链接:https://blog.csdn.net/mieleizhi0522/article/details/82142856 ,今天在写python爬虫的时候,循环的时候用到了yield,于是搜 ...

  4. css3中user-select的用法详解

    css3中user-select的用法详解 user-select属性是css3新增的属性,用于设置用户是否能够选中文本.可用于除替换元素外的所有元素,以下是user-select的主要用法和注意事项 ...

  5. C#中string.format用法详解

    C#中string.format用法详解 本文实例总结了C#中string.format用法.分享给大家供大家参考.具体分析如下: String.Format 方法的几种定义: String.Form ...

  6. c++中vector的用法详解

    c++中vector的用法详解 vector(向量): C++中的一种数据结构,确切的说是一个类.它相当于一个动态的数组,当程序员无法知道自己需要的数组的规模多大时,用其来解决问题可以达到最大节约空间 ...

  7. php中setcookie函数用法详解(转)

    php中setcookie函数用法详解:        php手册中对setcookie函数讲解的不是很清楚,下面是我做的一些整理,欢迎提出意见.        语法:        bool set ...

  8. JavaScript中return的用法详解

    JavaScript中return的用法详解 最近,跟身边学前端的朋友了解,有很多人对函数中的this的用法和指向问题比较模糊,这里写一篇博客跟大家一起探讨一下this的用法和指向性问题. 1定义 t ...

  9. Mysql中limit的用法详解

    Mysql中limit的用法详解 在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,为我们提供了limit这样一个功能. SELECT * FROM table LIMIT [offset ...

随机推荐

  1. plSql读取Oracle数据库中文乱码

    新建环境变量,设置变量名:NLS_LANG,变量值:SIMPLIFIED CHINESE_CHINA.ZHS16GBK,确定即可

  2. Java 开源博客 Solo 1.6.0 发布 - 新后台

    简介 Solo 是一款一个命令就能搭建好的 Java 开源博客系统,并内置了 15+ 套精心制作的皮肤.除此之外,Solo 还有着非常活跃的社区,文章分享到社区后可以让很多人看到,产生丰富的交流互动. ...

  3. <Android 应用 之路> MPAndroidChart~PieChart

    简介 MPAndroidChart是PhilJay大神给Android开发者带来的福利.MPAndroidChart是一个功能强大并且使用灵活的图表开源库,支持Android和IOS两种,这里我们暂时 ...

  4. numpy数组的创建

    创建数组 创建ndarray 创建数组最简单的方法就是使用array函数.它接收一切序列型的对象(包括其他数组),然后产生一个新的含有传入数据的Numpy数组. array函数创建数组 import ...

  5. Python语言程序设计学习 之 了解Python

    Python简介 Python是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. Python是纯粹的自由软件,源代 ...

  6. Linux扩展根目录下的空间

    自己通过root创建了一个新用户,然而当我使用这个新用户时发现,/home/my中的空间只有几十M,完全不能满足我的使用,所以通过下面的方法扩展根下的空间. 我的本次操作,参考于 http://www ...

  7. winform ComboBox控件反选

    winform ComboBox控件反选:int index = comboBox1.FindString(textBox2.Text); comboBox1.SelectedIndex = inde ...

  8. 让UpdatePanel支持文件上传(2):服务器端组件 .

    我们现在来关注服务器端的组件.目前的主要问题是,我们如何让页面(事实上是ScriptManager控件)认为它接收到的是一个异步的回送?ScriptManager控件会在HTTP请求的Header中查 ...

  9. POP3、SMTP端口(SSL、TSL)

    POP3服务器地址: 110           995 支持SSLSMTP服务器地址: 25            465 或者 587 支持SSL(TSL) 465端口是SSL/TLS通讯协议的 ...

  10. Python学习---网络编程 1217【all】

    OSI七层模型: 物理层, 数据链路层, 网络层,传输层,会话层,表达层,应用层 应用层:TFTP,HTTP,SNMP,FTP,SMTP,DNS,Telnet 等等 传输层:TCP,UDP 网络层:I ...