• .NET HttpWebRequest、WebClient、HttpClient


    HttpWebRequest类与HttpRequest类的区别
    HttpRequest类的对象用于服务器端【Request.QueryString、Request.From、Request[],Rquest.Params】,获取客户端传来的请求的信息,包括HTTP报文传送过来的所有信息。
    而HttpWebRequest用于客户端[请求服务器的],拼接请求的HTTP报文并发送等。
    HttpWebRequest这个类非常强大,强大的地方在于它封装了几乎HTTP请求报文里需要用到的东西,以致于能够能够发送任意的HTTP请求并获得服务器响应(Response)信息。
    HttpWebRequest:
    继承 WebRequest
    命名空间: System.Net,这是.NET创建者最初开发用于使用HTTP请求的标准类。使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。HttpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。
     //POST方法
    public static string HttpPost(string Url, string postDataStr)
    {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    request.Method = “POST”;
    request.ContentType = “application/x-www-form-urlencoded”;
    Encoding encoding = Encoding.UTF8;
    byte[] postData = encoding.GetBytes(postDataStr);
    request.ContentLength = postData.Length;
    Stream myRequestStream = request.GetRequestStream();
    myRequestStream.Write(postData, 0, postData.Length);
    myRequestStream.Close();
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream myResponseStream = response.GetResponseStream();
    StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);
    string retString = myStreamReader.ReadToEnd();
    myStreamReader.Close();
    myResponseStream.Close();

    return retString;
    }
    //GET方法
    public static string HttpGet(string Url, string postDataStr)
    {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == “” ? “” : “?”) + postDataStr);
    request.Method = “GET”;
    request.ContentType = “text/html;charset=UTF-8”;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream myResponseStream = response.GetResponseStream();
    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(“utf-8”));
    string retString = myStreamReader.ReadToEnd();
    myStreamReader.Close();
    myResponseStream.Close();
    return retString;
    }

    WebClient:
    public abstract class WebRequest : MarshalByRefObject, ISerializable
    public class HttpWebRequest : WebRequest, ISerializable
    public class WebClient : Component
    命名空间System.NetWebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,**Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。**使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。
    在这里插入图片描述

    public class WebClientHelper
    {
    public static string DownloadString(string url)
    {
    WebClient wc = new WebClient();
    //wc.BaseAddress = url; //设置根目录
    wc.Encoding = Encoding.UTF8; //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码
    string str = wc.DownloadString(url);
    return str;
    }
    public static string DownloadStreamString(string url)
    {
    WebClient wc = new WebClient();
    wc.Headers.Add(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36”);
    Stream objStream = wc.OpenRead(url);
    StreamReader _read = new StreamReader(objStream, Encoding.UTF8); //新建一个读取流,用指定的编码读取,此处是utf-8
    string str = _read.ReadToEnd();
    objStream.Close();
    _read.Close();
    return str;
    }

    public static void DownloadFile(string url, string filename)
    {
      WebClient wc = new WebClient();
      wc.DownloadFile(url, filename);   //下载文件
    }
    
    public static void DownloadData(string url, string filename)
    {
      WebClient wc = new WebClient();
      byte [] bytes = wc.DownloadData(url);  //下载到字节数组
      FileStream fs = new FileStream(filename, FileMode.Create);
      fs.Write(bytes, 0, bytes.Length); 
      fs.Flush();
      fs.Close();
    }
    
    public static void DownloadFileAsync(string url, string filename)
    {
      WebClient wc = new WebClient();
      wc.DownloadFileCompleted += DownCompletedEventHandler;
      wc.DownloadFileAsync(new Uri(url), filename);
      Console.WriteLine("下载中。。。");
    }
    private static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
    {
      Console.WriteLine(sender.ToString());  //触发事件的对象
      Console.WriteLine(e.UserState);
      Console.WriteLine(e.Cancelled);
      Console.WriteLine("异步下载完成!");
    }
    
    public static void DownloadFileAsync2(string url, string filename)
    {
      WebClient wc = new WebClient();
      wc.DownloadFileCompleted += (sender, e) =>
      {
        Console.WriteLine("下载完成!");
        Console.WriteLine(sender.ToString());
        Console.WriteLine(e.UserState);
        Console.WriteLine(e.Cancelled);
      };
      wc.DownloadFileAsync(new Uri(url), filename);
      Console.WriteLine("下载中。。。");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    }
    HttpClient:
    public class HttpClient : HttpMessageInvoker
    HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为 System.Net.Http ,.NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的。HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。它适合用于多次请求操作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的HTTP请求。HttpClient有预热机制,第一次进行访问时比较慢,所以不应该用到HttpClient就new一个出来,应该使用单例或其他方式获取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();
        }
    
        /// 
        /// Get请求
        /// 
        /// 
        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);
        }
    
        /// 
        /// Post请求
        /// 
        /// 
        /// 
        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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    注意:因为HttpClient有预热机制,第一次进行访问时比较慢,所以我们最好不要用到HttpClient就new一个出来,应该使用单例或其他方式获取HttpClient的实例
    在这里插入图片描述

  • 相关阅读:
    java版工程管理系统Spring Cloud+Spring Boot+Mybatis实现工程管理系统源码
    想知道如何将PDF合并成一个?这里有三个简单的方法分享
    【Node.js从基础到高级运用】七、基本的网络编程
    nvm使用的注意事项和常用命令。
    day26 java lambda
    【彩色图像处理GUI】各种颜色映射、重新调整大小和更改分辨率、伽玛校正,对比度,反转颜色(Matlab代码实现)
    在 Mac 客户端 C++ 代码中使用 breakpad
    如何使用做一个弹幕效果
    进程与线程
    软考知识点---10数据库基础
  • 原文地址:https://blog.csdn.net/u013400314/article/details/126641741