2016-11-30 63 views
0

我正在使用我的c#应用向网页发送请求。在发送任何请求之前,我必须登录此网页。每次我想要做一些工作时,我都希望避免记录,所以我在VARBINARY列中将cookie存储在sql server数据库中。我必须每次更新每个cookie吗?

比方说,我送50 POST requests每天:

private string getRequest(string url, string postData = "") 
     { 
      try 
      { 
       System.Net.ServicePointManager.Expect100Continue = true; 
       StreamReader reader; 
       var request = WebRequest.Create(url) as HttpWebRequest; 
       request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"; 
       request.CookieContainer = Cookie; 
       request.AllowAutoRedirect = true; 
       request.ContentType = "application/x-www-form-urlencoded"; 
       request.Headers.Add("X-Requested-With", "XMLHttpRequest"); 
       postData = Uri.EscapeUriString(postData); 
       request.Method = "POST"; 
       request.ContentLength = postData.Length; 
       Stream requestStream = request.GetRequestStream(); 
       Byte[] postBytes = Encoding.ASCII.GetBytes(postData); 

       requestStream.Write(postBytes, 0, postBytes.Length); 
       requestStream.Close(); 

       HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
       foreach (Cookie tempCookie in response.Cookies) 
       { 
        Cookie.Add(tempCookie); 
       } 
       reader = new StreamReader(response.GetResponseStream()); 
       string readerReadToEnd = reader.ReadToEnd(); 
       response.Close(); 

       database.updateCookie(AccountId, Cookie); //here I am updating the cookies 

       return readerReadToEnd; 
      } 
      catch { return ""; } 

我真的需要每个请求后更新Cookies?或者,也许我可以在发送50 POST requests后只更新我的cookie一次?

我在问,因为有时我的饼干会持续几天,有时他们会在1分钟后死亡。我不知道为什么以及如何避免这种情况。

我需要储存最新的曲奇吗?或者我可以每次都使用相同的曲奇吗?

+0

这取决于服务器发送的cookie。 – SLaks

+0

为什么你需要在你的数据库中存储cookies?如果你把它们存储在数据库中,Cookies也属于客户端机器,客户端机器上存储的是什么? –

+0

@SeanLange因为我有时会重启我的电脑。我想在数据库中存储cookie以避免日志记录。 – Dawvawd

回答

0

每个网站决定特定cookie的有效期限。因此,您需要分别为每个网站获取该信息才能正确执行此操作。注意cookie上的“过期”(在“响应的set-cookie”标题中)可能会为您提供有关cookie何时保证到期的初步指导。

常见到期/有效期范围:

  • 身份验证cookie - 10分钟至1天
  • ASP.Net会话状态 - 由20分钟
  • CSRF保护 - 可能更新每个响应
+0

嗯,但如果我输入例如Stackoverflow 7天后,我仍然记录。我想在我的C#应用​​程序中做同样的事情。如果我发送另一个请求例如3天后,我想已经登录在我的C#应用​​程序。 – Dawvawd

+0

@Dawvawd“common”!=“every one one”...随时了解具体网站如何处理身份验证和破解...请注意,某些网站提供了适当的API以访问来自非网络应用程序的信息 - 具体取决于你的目标网站可能是更好的方法,而不是希望在抓取时获得正确的cookies。 –

相关问题