C# httpwebrequest with many request

本文关键字:request many with httpwebrequest | 更新日期: 2023-09-27 18:34:26

我有列表词,我需要在webrequest POST方法上发送所有这些词像这里 :要请求的此函数>

   private void RequesteUrl(string word)
    {
     //   try
       // {

            CookieContainer WeBCookies = new CookieContainer();
            HttpWebRequest url = (HttpWebRequest)WebRequest.Create("http://mbc.com/index.php");
            url.Method = "POST";
            url.UserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:44.0) Gecko/20100101 Firefox/44.0";
           url.Referer = "http://mbc.com/index.php?";
            var PostData =  User.Text + "&password=" + word;
            var Data = Encoding.ASCII.GetBytes(PostData);
            url.ContentLength = Data.Length;
            url.Host = "www.mbc.com";
            url.ContentType = "application/x-www-form-urlencoded";
          //  url.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie);
            url.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            url.KeepAlive = true;

            url.Headers.Add("Cookie: "+tryit);
            using (var stream = url.GetRequestStream())
            {
                stream.Write(Data, 0, Data.Length);
            }
            HttpWebResponse WebResponse = (HttpWebResponse)url.GetResponse();
            int status = (int)WebResponse.StatusCode;
            Stream ST = WebResponse.GetResponseStream();
            StreamReader STreader = new StreamReader(ST);
            string RR = STreader.ReadToEnd();

           // MessageBox.Show (status.ToString() + "   " + word);
    //    }
     //   catch (Exception ex)
     //   {
      //      MessageBox.Show(ex.Message);
     //   }
    }

我用它来加载:

 foreach (string selectword in Lists)
        {
            RequesteUrl(selectword);
  }

但是对于每个列表都不完整,他只从列表中做两个!

C# httpwebrequest with many request

是的,原因是您在请求完成后没有释放资源。由于 HTTP/1.1 只允许每个服务器同时连接两个连接,因此在两次请求后,可用连接将用完。这就是它挂起的原因。

你需要关闭HttpWebResponse,也是关闭流阅读器和流的好主意。

using(HttpWebResponse WebResponse = (HttpWebResponse)url.GetResponse())
{
            int status = (int)WebResponse.StatusCode;
            using(Stream ST = WebResponse.GetResponseStream())
            using(StreamReader STreader = new StreamReader(ST))
                string RR = STreader.ReadToEnd();
}