---
title: ".net提供的5种request-response方法一"
author: "starnc"
date: "2009-09-06T17:16:34Z"
tags: []
slug: "net-5-request-response"
draft: false
lastmod: "2009-09-06T17:20:55Z"
id: 463608
url: "https://starnc.iteye.com/blog/463608"
---

.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);
        }
    }
}
```

 

得到结果如下图

 

![](http://dl.iteye.com/upload/attachment/143460/f33b93ba-f095-3ea3-9818-b6490194c38d.jpg)  
 

 

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

 

 

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