0

我需要使用 C# 编程语言(Microsoft Visual Studio 2010)进行一些站点操作。它是网站“ http://m.vk.com ”。我在这个网站上授权。一切都很正常。授权后的第一个网页是我的个人资料页面。但是当我转到该站点的另一个页面时,我失去了授权。显示了另一个站点页面,但处于非授权模式。我将 cookie 文件保存并写入另一个查询。我接下来编写我的 C# 编程代码:

我使用了这些指令:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;

它是主按钮按下后启动的主功能代码:

private void button1_Click(object sender, EventArgs e)
{
     string login = textBox1.Text;
     string pass = textBox2.Text;
     bool avt = http_auth_vk(login, pass);

     if (avt == true)
     {
         toolStripStatusLabel1.Text = "Succes authorization !";
     }
     else 
     {
         toolStripStatusLabel1.Text = "Authorization data incorrect !";
     }
 }

这是函数“http_auth_vk”:

    public bool http_auth_vk(string login, string pass)
    {
        //*****************************
        //Получаем action_url
        //*****************************
        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        System.Net.WebRequest reqGET = System.Net.WebRequest.Create("http://m.vk.com/");
        System.Net.WebResponse resp = reqGET.GetResponse();
        System.IO.Stream stream = resp.GetResponseStream();
        System.IO.StreamReader sr = new System.IO.StreamReader(stream);
        string s = sr.ReadToEnd();


        //*****************************
        //Парсим
        //*****************************
        // Создаём экземпляр класса
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        // Загружаем в класс (парсер) наш html
        doc.LoadHtml(s);
        // Извлекаем значения
        HtmlNode bodyNode = doc.DocumentNode.SelectSingleNode("//div[@class='cont']/form");
        // Выводим на экран значиение атрибута src
        // у изображения, которое находилось
        // в теге <div> в слассом bla
        string result1 = bodyNode.Attributes["action"].Value;

        //*****************************
        //POST запрос
        //*****************************
        var cookies = new CookieContainer();
        ServicePointManager.Expect100Continue = false;
        var request = (HttpWebRequest)WebRequest.Create(result1);
        request.CookieContainer = cookies;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        using (var requestStream = request.GetRequestStream())
        using (var writer = new StreamWriter(requestStream))
        {
            writer.Write("email=" + login + "&pass=" + pass);
        }

        using (var responseStream = request.GetResponse().GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            var result = reader.ReadToEnd();

            //*****************************
            //Парсим, поиск ID
            //*****************************                 
            HtmlAgilityPack.HtmlDocument doc2 = new HtmlAgilityPack.HtmlDocument();                
            doc2.LoadHtml(result);
            string result2;
            try
            {
                //textBox3.Text = result;

                HtmlNode bodyNode2 = doc2.DocumentNode.SelectSingleNode("//div[@class='user_wrap']/a");
                result2 = bodyNode2.Attributes["href"].Value.Substring(3);
                //Если ID найден, то авторизация удалась



                //ПЕРЕХОД НА СТРАНИЦУ ГРУППЫ

                //string sLocation = myHttpWebResponse.Headers["Location"];

                // получам cookie
                string sCookies = "";
                if (!String.IsNullOrEmpty(resp.Headers["Set-Cookie"]))
                {
                    sCookies = resp.Headers["Set-Cookie"];
                }

                MessageBox.Show(sCookies);

                // формируем запрос
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://m.vk.com/id100669061");
                //myHttpWebRequest.Proxy = new WebProxy("127.0.0.1", 8888);

                myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; MyIE2;";
                myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                myHttpWebRequest.Headers.Add("Accept-Language", "ru");
                myHttpWebRequest.ContentType = "text/plain";

                if (!String.IsNullOrEmpty(sCookies))
                {
                    myHttpWebRequest.Headers.Add(HttpRequestHeader.Cookie, sCookies);
                }

                // выполняем запрос
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();


                StreamReader myStreamReader = new StreamReader(myHttpWebResponse.GetResponseStream(), Encoding.GetEncoding(1251));

                textBox3.Text = myStreamReader.ReadToEnd();


                MessageBox.Show(myStreamReader.ReadToEnd());


                //Console.WriteLine(myStreamReader.ReadToEnd());
                //Console.ReadKey();



                return true;
            }
            catch
            {
                //textBox3.Text = result;

                //Если ID не науден, то авторизация не удалась
                MessageBox.Show("Authorization error !");

                return false;
            }
        }
    }

下一页通过后如何保存授权?

4

1 回答 1

0

经过一番调查,我相信我发现了你的问题。.NET 框架将为您处理 cookie,您无需担心设置 cookie 或保存 cookie 以供以后使用,但您需要为所有请求使用相同的 CookieContainer。

因此,首先设置您要使用的 cookie 容器:

var cookies = new CookieContainer();

您也可以删除所有使用 sCookies 的代码。

string sCookies = "";
if (!String.IsNullOrEmpty(resp.Headers["Set-Cookie"]))
{
      sCookies = resp.Headers["Set-Cookie"];
}
MessageBox.Show(sCookies);

在第二个/第三个请求中,而不是这样:

        if (!String.IsNullOrEmpty(sCookies))
        {
            myHttpWebRequest.Headers.Add(HttpRequestHeader.Cookie, sCookies);
        }

你需要有这个(CookieContainer)

myHttpWebRequest.CookieContainer = cookies;
于 2012-08-08T11:44:01.870 回答