c# - 如何以编程方式检索 html 重定向网页?

标签 c# httpwebrequest

我已经完成此代码来登录、检索和显示网页:

  // login info array
        string postData = "user_name=tler";
        postData += "&user_password=lodvader";
        byte[] data = Encoding.ASCII.GetBytes(postData);

        // web request
        WebRequest req = WebRequest.Create("http://www.lol.com/login.php");
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = data.Length;

        // stream response to string
        Stream newStream = req.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));

        string responseString = reader.ReadToEnd();

        // retrieve text within title
        Regex rx = new Regex(@"(?<=<title>).+?(?=</title>)");

        var variable = rx.Matches(responseString);

        // output
        Console.WriteLine(variable[0]);

        Console.ReadLine();

但是,登录后的以下页面是一个 html 重定向,如下所示:

<meta http-equiv="refresh" content="3; URL="bb.php">

如何点击此链接并检索下一页?

最佳答案

只需向 bb.php 文件发送一个新的 WebRequest。确保您使用相同的 CookieContainer,因为我认为 login.php 使用基于 cookie 的 session 来记住您。查看HttpWebRequest.CookieContainer属性(property)。这需要您将 WebRequest 转换为 HttpWebRequest。

添加:(无法在评论中编写示例代码。)

我只是在编写代码,现在还没有校对...

var cookies = new CookieContainer(); 

var firstReq = (HttpWebRequest)WebRequest.Create(".../login.php");
firstReq.CookieContainer = cookies;

var secondReq = (HttpWebRequest)WebRequest.Create(".../bb.php");
secondReq.CookieContainer = cookies

关于c# - 如何以编程方式检索 html 重定向网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/630575/

相关文章:

c# - 服务结构: Authenticating with Azure KeyVault via cert: "KeySet does not exist"

.net - 使用客户端凭据通过 SSL 的 HttpWebRequest

c# - 如何使用 C# 并行发送 Web 请求。

c# - C#超时计算中*0x3e8是什么意思?

c# - 停止 Visual Studio 将数据库 MDF 复制到 bin

c# - 命名空间和子命名空间

c# - 具有无限数量的键但数量有限的对象的对象缓存

c# - 如果网络关闭,MessageReceiver.RegisterMessageHandler 会连续抛出异常

c# - 从 URL 获取主机域?

c# - WebRequest GetResponseStream 读取字节