【问题标题】:HttpWebRequest resp.Headers["Set-Cookie"] is nullHttpWebRequest resp.Headers["Set-Cookie"] 为空
【发布时间】:2012-09-29 15:47:51
【问题描述】:

更新 1: post/get headers 截图:http://imageshack.us/photo/my-images/826/getpost.png

我正在寻求有关网络请求的帮助。该请求的目的是登录站点并检索 Set-Cookie 标头。感谢您的帮助!

我正在尝试登录网站并使用以下代码检索 cookie 值。但是,Set-Cookie 标头始终为空:

static void Main(string[] args)
{
    string formUrl = "https://account.guildwars2.com/login";
    string formParams = string.Format("email={0}&password={1}", "xxx", "xxx");
    string cookieHeader;
    var req = (HttpWebRequest)WebRequest.Create(formUrl);
    req.Referer = "https://account.guildwars2.com/login";
    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";
    req.KeepAlive = true;
    byte[] bytes = Encoding.ASCII.GetBytes(formParams);
    req.ContentLength = bytes.Length;
    using (Stream os = req.GetRequestStream())
    {
        os.Write(bytes, 0, bytes.Length);
    }
    WebResponse resp = req.GetResponse();
    cookieHeader = resp.Headers["Set-Cookie"];
}

我不确定这是否与重定向有关,因为在 C# 应用程序中,response-uri 是“https://account.guildwars2.com/login?redirect_uri=/download

响应标头 Chrome

  • 内容长度:0
  • 内容类型:文本/html
  • 日期:2012 年 9 月 29 日星期六 15:07:30 GMT
  • 位置:下载
  • 服务器:Microsoft-IIS/7.5
  • 设置 Cookie:s=60B845F0-4E22-4A4B-890B-F3B885CEF9AE;域=guildwars2.com;路径=/;版本=1
  • X-Powered-By:ARR/2.5

来自 C# 应用程序的响应

  • 内容长度:7344
  • 内容类型:文本/html
  • 日期:2012 年 9 月 29 日星期六 15:42:44 GMT
  • 服务器:Microsoft-IIS/7.5
  • X-Powered-By:ARR/2.5

【问题讨论】:

  • 我认为您需要在发送之前将 httpWebRequest.CookieCollection 设置为新的 CookieCollection,可能是不使用 VS atm 时输入错误。
  • 我试过 req.CookieContainer = new CookieContainer();但没有添加任何内容

标签: c# cookies webrequest


【解决方案1】:

默认情况下,HttpWebRequest 自动跟随 HTTP 重定向响应,这会阻止您捕获原始响应中的 Set-Cookie 标头。要禁用此行为,请在发送请求之前将 AllowAutoRedirect 设置为 false

req.AllowAutoRedirect = false;

【讨论】:

    【解决方案2】:

    您可以尝试使用这种方式检索 cookie:

    CookieContainer cookies = new CookieContainer();
    
    WebResponse resp = req.GetResponse();
    
    CookieCollection cookieCollection = cookies.GetCookies(request.RequestUri);
    

    【讨论】:

    • 谢谢,但 cookie 集合为空。我开始认为它与重定向有关。当我在 google 中调试时,它首先以状态 303(重定向)POST 到登录站点,然后以状态 200(OK)获取下载站点。
    猜你喜欢
    • 2011-07-21
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    相关资源
    最近更新 更多