C#之 http请求

今天,遇到一件事情,同事A优化了公司生成迭代报告文档工具的代码。

同事A将代码分享出来以后,发现问题如下:同一个http的request请求,第一次response得到失败的请求结果后,该开发人员使用了同一个request请求,连续循环20次,企图再次能够成功response到结果。

众所周知,http协议中,发起一次request请求,无论失败成功,response都会返回,由于http的无状态性,这次会话就算结束了。服务器端已经自动把客户端的这次电话挂断了。

客户端如果有需要,打算再次通话,需要再次拨打电话,发起请求,然后服务器依然response一次,电话挂断。仅此而已。

教训:以下代码,while循环自第二次执行开始,就是错误的。

          这个考察的是最基本的知识点,http通讯

            try
            {
                string url = "http://www.baidu.com";
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.ContentType = "application/json";
                request.Accept = "text/html,application/xhtml+xml,*/*";
                request.Method = "Get";
                request.Timeout = 30000;
                int i = 0;
                while (i < 20)
                {
                    using (WebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        Console.Write(response.ToString());
                    }
                    i++;
                }

            }
            catch (Exception ex)
            {
                throw;
            }

猜你喜欢

转载自blog.csdn.net/airingyuan/article/details/105675624
今日推荐