【问题标题】:HTTPS C# POST 302 MovedHTTPS C# POST 302 已移动
【发布时间】:2010-11-04 21:43:03
【问题描述】:

我正在尝试创建一个脚本来登录网页并获取报告 - 一切都很好,除了 - 我得到了一个

HTTP/1.1 302 MovedTemporarily
Date: Mon, 22 Jun 2009 13:22:04 GMT
Server: Server
x-some-id-1: 0J3X3VBBCGNJG9V46G5D
x-some-id-2: BtQ4SsDhbryWgiVNFcVpMbt898GuPIBaWuGwAWjvsyI=
Set-cookie: session-id-time=1246258800l; path=/; domain=.example.com; expires=Mon Jun 29 07:00:00 2009 GMT
Set-cookie: session-id=179-5933843-4704124; path=/; domain=. example.com; expires=Mon Jun 29 07:00:00 2009 GMT
Location: https://example.com
Vary: Accept-Encoding,User-Agent
nnCoection: close
Content-Type: text/html; charset=UTF-8
Content-Length: 0

响应,我不知道如何阻止它。我试过设置

httpwebrequest.allowautoredirect "True" 和 "False" 都没有帮助。

这让我发疯了,因为我可以通过 https:// 登录网站,但后来我得到了返回?

【问题讨论】:

    标签: c# https httpwebrequest http-status-code-302


    【解决方案1】:

    我被这个问题困扰了很长时间 - 很高兴我能提供帮助。阅读这篇文章

    http://www.byteblocks.com/page/How-to-submit-requests-to-web-sites-programatically-using-HttpWebRequest.aspx

    关键问题是您不能使用启用了自动重定向的 HttpWebRequest 来执行涉及 302 和 cookie 的登录过程,因为直到整个过程结束时才会设置 cookie。

    解决方案是禁用自动重定向并逐步手动实现整个登录过程(获取 302 重定向响应的“Location”标头以及“Set-cookie”标头,然后通过根据需要将这些步骤分解为连续的步骤)。

    您的 cookie 容器需要沿途抓取所有 cookie 并在最后提交。如果你得到一个 302 - 你会撞到墙上,想知道为什么你总是在登录页面结束。

    【讨论】:

      【解决方案2】:

      我知道,这个问题很老,但谷歌点在这里。所以,这是WebClient 的另一种解决方案。

      public class CookieAwareWebClient : WebClient
      {
          private CookieContainer cookie = new CookieContainer();
      
          protected override WebRequest GetWebRequest(Uri address)
          {
              WebRequest request = base.GetWebRequest(address);
              if (request is HttpWebRequest)
              {
                  (request as HttpWebRequest).CookieContainer = cookie;
                  (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1300.0 Iron/23.0.1300.0 Safari/537.11";
              }
              return request;
          }
      }
      

      然后创建WebClient 对象CookieAwareWebClient wc = new CookieAwareWebClient(); 并做任何你需要的事情。

      编辑:也可以通过 HTTP 和 HTTPS 工作。

      【讨论】:

        猜你喜欢
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多