HttpWebRequest VS WebRequest VS WebClient VS HttpClient

这篇博客详细对比了HttpWebRequest、WebRequest、WebClient和HttpClient在执行HTTP请求时的用法,包括GET和POST操作,探讨了各自的特性和适用场景。

 

WebRequest  Get

  #region  WebRequest  Get

        /// <summary>
        /// http://localhost:15325/api/ImitateHttp/WebRequestGet?Name0="NameLi"
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        [System.Web.Http.HttpGet]
        public string WebRequestGet(string Name0)
        {
            string strReturn = "";// objWeather.city;
            try
            {
                //参数url化
                String city = "徐州";
                //拼地址
                String apiUrl = "https://www.sojson.com/open/api/weather/json.shtml?city=" + city;
                WebRequest myWebRequest = WebRequest.Create(apiUrl);
                

                WebResponse myWebResponse = myWebRequest.GetResponse();
                Stream ReceiveStream = myWebResponse.GetResponseStream();
                string responseStr = "";
                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                myWebResponse.Close();
                
                RootClass objWeather = Newtonsoft.Json.JsonConvert.DeserializeObject<RootClass>(responseStr);
                strReturn = responseStr;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return strReturn;
        }

        #endregion

 

WebRequest  Post

 #region  WebRequest  Post

        /// <summary>
        /// http://localhost:15325/api/ImitateHttp/WebRequestPost
        /// 
        /// http://lbsyun.baidu.com/index.php?title=yingyan/api/v3/entity
        /// 
        /// {"AK":"SoEMqok1s5IKt5EDb5VARNr6WoKk74h2","service_id":1805228,"entity_name":"entityName","entity_desc":"entityDesc","province":"provinceJS","city":"cityXZ","sn":""}
        /// </summary>
        /// <param name="Name0"></param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public string WebRequestPost([FromBody]BaiduEntityRequest objRequest)
        {
            string strReturn = "";// objWeather.city;
            try
            {
                //请求路径
                string url = "http://yingyan.baidu.com/api/v3/entity/add";

                //定义request并设置request的路径
                WebRequest request = WebRequest.Create(url);
                request.Method = "post";

                // objRequest  可以不从请求给,测试的时候在这里写死 
                //BaiduEntityRequest objRequest = new BaiduEntityRequest();
                //objRequest.ak = "SoEMqok1s5IKt5EDb5VARNr6WoKk74h2";
                //objRequest.service_id = 1805228;
                //objRequest.entity_name = "entityName";
                //objRequest.entity_desc = "entityDesc";
                //objRequest.province = "provinceJS";
                //objRequest.city = "cityXZ";
                //objRequest.sn = "";


                //初始化request参数
                //string postData = "{ ID: \"1\", NAME: \"Jim\", CREATETIME: \"1988-09-11\" }";
                string po
### 抽象层级与封装程度 - **WebClient**:是一种更高级别的抽象,为简化常见任务而创建,相当于封装了 request 和 response 方法,使用更为简单,减少了很多细节,代码量也比较少,但缺少基本的 header、timeout 设置等,过可通过继承 HttpWebRequest 来实现这些功能。它和 HttpWebRequest 继承的是同类,在继承上没有关系[^1]。 - **HttpWebRequest**:属于低级 API,提供对 HTTP 请求的细粒度控制,支持多种 HTTP 方法和高级功能,开发人员可以对请求的各个方面进行详细设置[^2]。 - **HttpClient**:是现代且功能强大的 HTTP 客户端,在 .NET 4.5 引入,属于较为高级的抽象,提供了更简洁的 API 来处理 HTTP 请求,同时具备可配置性强等特点[^3]。 ### 异步支持 - **WebClient**:支持异步操作,适合需要异步操作、简单的 GET 和 POST 请求场景,适合长时间运行的操作[^2]。 - **HttpWebRequest**:同样支持异步操作,适用于需要细粒度控制但需要异步操作的场景[^2]。 - **HttpClient**:支持异步操作,适合长时间运行的操作、复杂的 HTTP 请求以及需要高级配置的场景,通过异步方法可以提高程序的响应性能和资源利用率[^2]。 ### 性能表现 - **WebClient**:使用可能比 HttpWebRequest 直接使用更慢(大约几毫秒),因为它在封装过程中会有一些额外的开销,但使用简单,代码量少[^1]。 - **HttpWebRequest**:由于是低级 API,直接操作请求和响应,性能上相对较为高效,但需要处理更多的细节,代码量相对较多。 - **HttpClient**:具有连接复用功能,通过连接池提高性能,适合多次请求操作。过它有预热机制,第一次进行访问时比较慢,所以建议使用单例或其他方式获取 HttpClient 的实例[^3]。 ### 功能特性 - **WebClient**:功能有限,例如缺少基本的 header、timeout 设置等,过这些可以通过继承 HttpWebRequest 来实现[^1]。 - **HttpWebRequest**:功能丰富,支持多种 HTTP 方法和高级功能,如自定义请求头、超时设置等,开发人员可以对请求进行详细的定制[^2]。 - **HttpClient**:可配置性强,支持设置超时、取消请求、重试策略等高级功能,还支持异步操作和连接复用,能更好地适应复杂的网络请求场景[^2]。 ### 代码示例对比 #### WebClient ```csharp using System; using System.Net; class Program { static void Main() { using (WebClient client = new WebClient()) { string response = client.DownloadString("https://www.example.com"); Console.WriteLine(response); } } } ``` #### HttpWebRequest ```csharp using System; using System.IO; using System.Net; class Program { static void Main() { string url = "https://www.example.com"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { string responseText = reader.ReadToEnd(); Console.WriteLine(responseText); } } } } } ``` #### HttpClient ```csharp using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main() { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("https://www.example.com"); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值