WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别

1.WebRequest和HttpWebRequest

  WebRequest 的命名空间是: System.Net ,它是HttpWebRequest的抽象父类(还有其他子类如FileWebRequest ,FtpWebRequest),WebRequest的子类都用于从web获取资源。HttpWebRequest利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来对数据进行获取和提交

一个栗子:

        static void Main(string[] args)
        {
            // 创建一个WebRequest实例(默认get方式)        
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
            //可以指定请求的类型
            //request.Method = "POST";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(response.StatusDescription);
            // 接收数据
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);
            // 关闭stream和response
            reader.Close();
            dataStream.Close();
            response.Close();
        }

运行后输出百度网页的html字符串,如下:

2.HttpRequest

  HttpRequest类的命名空间是:System.Web,它是一个密封类,其作用是让服务端读取客户端发送的请求,我们最熟悉的HttpRequest的实例应该是WebForm中Page类的属性Request了,我们可以轻松地从Request属性的QueryString,Form,Cookies集合获取数据中,也可以通过Request["Key"]获取自定义数据,一个栗子:
            protected void Page_Load(object sender, EventArgs e)
            {
                //从Request中获取商品Id
                string rawId = Request["ProductID"];
                int productId;
                if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))
                {
                    //把商品放入购物车
                    using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
                    {
                        usersShoppingCart.AddToCart(productId);
                    }
                }
                else
                {
                    throw new Exception("Tried to call AddToCart.aspx without setting a ProductId.");
                }
                //跳转到购物车页面
                Response.Redirect("ShoppingCart.aspx");
            }

3.WebClient

  命名空间是System.Net,WebClient很轻量级的访问Internet资源的类,在指定uri后可以发送和接受数据。WebClient提供了 DownLoadData,DownLoadFile,UploadData,UploadFile 方法,同时通过了这些方法对应的异步方法,通过WebClient我们可以很方便地上传和下载文件。

简单使用:

static void Main(string[] args)
{
            WebClient wc = new WebClient();
            wc.BaseAddress = "http://www.baidu.com/";   //设置根目录
            wc.Encoding = Encoding.UTF8;                //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码
            string str = wc.DownloadString("/");        //字符串形式返回资源
            Console.WriteLine(str);


            //----------------------以下为OpenRead()以流的方式读取----------------------
            wc.Headers.Add("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            wc.Headers.Add("Accept-Language", "zh-cn");
            wc.Headers.Add("UA-CPU", "x86");
            //wc.Headers.Add("Accept-Encoding","gzip, deflate");    //因为我们的程序无法进行gzip解码所以如果这样请求获得的资源可能无法解码。当然我们可以给程序加入gzip处理的模块 那是题外话了。
            wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
            //Headers   用于添加添加请求的头信息
            Stream objStream = wc.OpenRead("?tn=98050039_dg&ch=1");             //获取访问流
            StreamReader _read = new StreamReader(objStream, Encoding.UTF8);    //新建一个读取流,用指定的编码读取,此处是utf-8
            Console.Write(_read.ReadToEnd());                                   //输出读取到的字符串

            //------------------------DownloadFile下载文件-------------------------------
            wc.DownloadFile("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.jpg", @"D:123.jpg"); //将远程文件保存到本地 

//------------------------DownloadFile下载到字节数组-------------------------------
byte[] bytes = wc.DownloadData("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif");
FileStream fs
= new FileStream(@"E:123.gif", FileMode.Create);
fs.Write(bytes,
0, bytes.Length); fs.Flush();
WebHeaderCollection whc
= wc.ResponseHeaders;
//获取响应头信息
foreach (string s in whc) {
Console.WriteLine(s
+ ":" + whc.Get(s));
}

Console.ReadKey();
}

一个使用WebClient下载文件的栗子:

        static void Main(string[] args)
        {
            
            WebClient wc = new WebClient();

            //直接下载
            Console.WriteLine("直接下载开始。。。");
            wc.DownloadFile("http://www.kykan.cn/d/file/djgz/20170506/8e207019d3a8e6114bfc7f50710211c1.xlsx", @"D:ku.xlsx");
            Console.WriteLine("直接下载完成!!!");   //下载完成后输出 下载完成了吗?

            //异步下载
            wc.DownloadFileAsync(new Uri("http://www.kykan.cn/d/file/djgz/20170506/8e207019d3a8e6114bfc7f50710211c1.xlsx"), @"D:ku.xlsx");
            wc.DownloadFileCompleted += DownCompletedEventHandler;
            Console.WriteLine("do something else...");
            Console.ReadKey();
        }

        public static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
        {
            Console.WriteLine("异步下载完成!");
        }

4.HttpClient

  HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为 System.Net.Http 。.NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的。HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。

   下边是一个使用控制台程序异步请求接口的栗子:

        static void Main(string[] args)
        {
            const string GetUrl = "http://xxxxxxx/api/UserInfo/GetUserInfos";//查询用户列表的接口,Get方式访问
            const string PostUrl = "http://xxxxxxx/api/UserInfo/AddUserInfo";//添加用户的接口,Post方式访问

            //使用Get请求
            GetFunc(GetUrl);

            UserInfo user = new UserInfo { Name = "jack", Age = 23 };
            string userStr = JsonHelper.SerializeObject(user);//序列化
            //使用Post请求
            PostFunc(PostUrl, userStr);
            Console.ReadLine();
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="path"></param>
        static async void GetFunc(string path)
        {
            //消息处理程序
            HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            HttpClient httpClient = new HttpClient();
            //异步get请求
            HttpResponseMessage response = await httpClient.GetAsync(path);
            //确保响应正常,如果响应不正常EnsureSuccessStatusCode()方法会抛出异常
            response.EnsureSuccessStatusCode();
            //异步读取数据,格式为String
            string resultStr = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultStr);
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        static async void PostFunc(string path, string data)
        {
            HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            HttpClient httpClient = new HttpClient(handler);
            //HttpContent是HTTP实体正文和内容标头的基类。
            HttpContent httpContent = new StringContent(data, Encoding.UTF8, "text/json");
            //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BasicAuth", Ticket);//验证请求头赋值
            //httpContent.Headers.Add(string name,string value) //添加自定义请求头

            //发送异步Post请求
            HttpResponseMessage response = await httpClient.PostAsync(path, httpContent);
            response.EnsureSuccessStatusCode();
            string resultStr = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultStr);
        }
    }

注意:因为HttpClient有预热机制,第一次进行访问时比较慢,所以我们最好不要用到HttpClient就new一个出来,应该使用单例或其他方式获取HttpClient的实例。上边的栗子为了演示方便直接new的HttpClient实例。

HttpClient还有很多其他功能,如附带Cookie,请求拦截等,可以参考https://www.cnblogs.com/wywnet/p/httpclient.html

参考文章:

1.https://www.cnblogs.com/wywnet/p/httpclient.html

2.https://www.cnblogs.com/kissdodog/archive/2013/02/19/2917004.html

3.https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?redirectedfrom=MSDN&view=netframework-4.7.2

原文地址:https://www.cnblogs.com/wyy1234/p/9837996.html