4

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

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:// 登录该网站,但后来我得到了返回?

4

2 回答 2

4

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

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 - 你会撞到墙上,想知道为什么你一直在登录页面结束。

于 2009-06-22T16:24:39.770 回答
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 工作。

于 2013-07-20T18:54:00.623 回答