c# - 有没有办法使用 WebClient 从受密码保护的位置而不是 Httprequest 获取登录 cookie?

标签 c# webclient

我目前正在使用以下代码获取网站的 cookie:

      bool IsLoginSuccessful = false;
  try
  {
    //Get Token and Authorization URL
    HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("https://updates.site.com/download");
    wr.AllowAutoRedirect = true;
    WebResponse response = wr.GetResponse();
    response.Close();
    string data = response.ResponseUri.OriginalString;
    string ssoToken = data.Split('=')[1];
    string authData = String.Format("ssousername={0}&password={1}&site2pstoretoken={2}", username, password, ssoToken);
    string ssoServer = response.ResponseUri.Scheme + "://" + response.ResponseUri.Host;
    string ssoAuthUrl = "sso/auth";

    // now let's get our cookie for the download
    byte[] dataBytes = Encoding.UTF8.GetBytes(authData);
    string url = ssoServer + "/" + ssoAuthUrl;
    wr = (HttpWebRequest)HttpWebRequest.Create(url);

    //MyCookies is a CookieContainer I use to store the login cookies
    wr.CookieContainer = MyCookies;
    wr.Method = "POST";
    wr.ContentLength = dataBytes.Length;
    wr.ContentType = "application/x-www-form-urlencoded";
    Stream dataStream = wr.GetRequestStream();
    dataStream.Write(dataBytes, 0, dataBytes.Length);
    dataStream.Close();
    response = wr.GetResponse();
    response.Close();

    if (wr.CookieContainer.Count > 0)
    {
      IsLoginSuccessful = true;
    }
  }

我想知道是否有一种方法可以使用 WebClient 或继承自它的类来获取 cookie 而不是使用 HttpRequest?

最佳答案

to obtain the cookie instead of using HttpRequest?

Cookie 是 HttpRequest 的属性(property):

int loop1, loop2;
HttpCookieCollection MyCookieColl;
HttpCookie MyCookie;

MyCookieColl = Request.Cookies;

// Capture all cookie names into a string array.
String[] arr1 = MyCookieColl.AllKeys;

// Grab individual cookie objects by cookie name. 
for (loop1 = 0; loop1 < arr1.Length; loop1++) 
{
   MyCookie = MyCookieColl[arr1[loop1]];
   Response.Write("Cookie: " + MyCookie.Name + "<br>");
   Response.Write ("Secure:" + MyCookie.Secure + "<br>");

   //Grab all values for single cookie into an object array.
   String[] arr2 = MyCookie.Values.AllKeys;

   //Loop through cookie Value collection and print all values. 
   for (loop2 = 0; loop2 < arr2.Length; loop2++) 
   {
      Response.Write("Value" + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
   }
}

关于c# - 有没有办法使用 WebClient 从受密码保护的位置而不是 Httprequest 获取登录 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14096782/

相关文章:

c# - 为什么 Context.RewritePath 维护查询字符串?

c# - 扩展静态方法和非扩展静态方法在使用上有什么区别

c# - 来自 webclient C# 的空答案

c# - 如何使用 webclient 读取通过 ajax 生成的内容?

c# - 在C#中使用DbParameter将数据插入SQL Server

c# - 是否可以使用带有内部连接的 ef core 5 运行原始 sql 并将数据具体化为一个类?

c# - 可以传递给 Environment.Exit 方法的默认值是什么?

c# - Windows 8 中不存在 WebClient 类

c# - 使用 Twitter API 1.1 oAuth 验证和请求用户的时间线

c# - 尝试捕捉不起作用