·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> .net提供的5种request-response方法一

.net提供的5种request-response方法一

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

.net提供的5种request-response方法一

.net提供了三种基本方法和两种底层方法来发送http请求和接收http响应,通过这些方法,我们可以模仿在浏览器地址栏输入URL地址访问网页的方法。我们发送http请求,接收服务器返回的响应(通常就是HTML网页)。由此对得到的网页进行分析,比如做自动化测试、或者抓取该网页上你感兴趣的东西,再放到自己程序里,总之应用很多,我能想到的,暂时就这么多。

五种方法分别是:

1.WebClient

2.WebRequest-WebResponse

3.HttpWebRequest-HttpWebResponse

4.TcpClient

5.Socket

其中前三种比较简单,后两者比较底层

本文先写第一种WebClient,比较简单,直接上代码

C#代码收藏代码
  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Text;
  5. usingSystem.Net;
  6. namespaceWebClientTest
  7. {
  8. classPRogram
  9. {
  10. staticvoidMain(string[]args)
  11. {
  12. stringuri="http://starnc.iteye.com/blog/404768";
  13. WebClientwc=newWebClient();
  14. Console.WriteLine("SendinganhttpGetrequestto"+uri);
  15. byte[]bResponse=wc.DownloadData(uri);
  16. stringstrResponse=Encoding.UTF8.GetString(bResponse);
  17. Console.WriteLine("HTTPresponseis:");
  18. Console.WriteLine(strResponse);
  19. }
  20. }
  21. }

得到结果如下图

这就是我们得到的网页源文件,和你直接在IE里访问那个URL的网页得到的结果是一样的,有了这个你可以干你喜欢干的事了。

本文参考了《.net软件自动化测试之道》,一本不错的书,大家应该看看。