`
starnc
  • 浏览: 142215 次
  • 性别: Icon_minigender_1
  • 来自: 火星
社区版块
存档分类
最新评论

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

    博客分类:
  • .NET
阅读更多

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

五种方法分别是:

1.WebClient

2.WebRequest-WebResponse

3.HttpWebRequest-HttpWebResponse

4.TcpClient

5.Socket

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

 

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace WebClientTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri="http://starnc.iteye.com/blog/404768";
            WebClient wc=new WebClient();
            Console.WriteLine("Sending an http Get request to"+uri);
            byte[] bResponse=wc.DownloadData(uri);
            string strResponse=Encoding.UTF8.GetString(bResponse);
            Console.WriteLine("HTTP response is: ");
            Console.WriteLine(strResponse);
        }
    }
}

 

得到结果如下图

 



 

 

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

 

 

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

  • 大小: 70.6 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics