Форум АНТИЧАТ

Форум АНТИЧАТ (https://forum.antichat.xyz/index.php)
-   С/С++, C#, Delphi, .NET, Asm (https://forum.antichat.xyz/forumdisplay.php?f=24)
-   -   Авторизация на сайте через C# (https://forum.antichat.xyz/showthread.php?t=179068)

FlyBird 15.02.2010 17:46

Авторизация на сайте через C#
 
В общем думаю, что тема поднималась не раз, но толком ничего не нашла. В гугле есть пара тем приятных, по их образу и писала, но что-то где-то явно не так.
Естественно свой код есть и я его приведу ниже.
Суть в том, что есть форма на сайте и она передает методом post логин, пароль и сервер. Я пытаюсь отправить через C# POST запрос на форму авторизации. На выходе у меня приходит что-то не понятное. абракадабра или html в каком-то шифре. Кто знает может в gzip :confused:

Код моего запроса приведен ниже.
Если у кого-то есть своим, то буду рада их почитать.
Код:

string _ContentLength = "user=LOGIN&password=******&server_select=1";

            // Делаем массив байтов
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] POSTArray = encoder.GetBytes(_ContentLength);

            // Готовим запрос
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(@"http://www.SITE.ru/index.php?action=login");
            System.Net.ServicePointManager.Expect100Continue = false;
            httpRequest.Method = "POST";
            httpRequest.ProtocolVersion = HttpVersion.Version10;
            httpRequest.Referer = "http://www.SITE.ru/index.php?action=login&user=LOGIN&password=******&server_select=1";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.Headers.Add("Accept-Language", "ru,en-us;q=0.7,en;q=0.3");
            httpRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            httpRequest.Headers.Add("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.7");
            httpRequest.Headers.Add("Keep-Alive", "115");
            //httpRequest.Headers.Add("Connection", "keep-alive");
            httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.2) Gecko/20100115 MRA 5.6 (build 03278) Firefox/3.6 sputnik unknown";
            httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            httpRequest.ContentLength = POSTArray.Length;
            httpRequest.KeepAlive = true;

            // Шлем запрос
            Stream stream = httpRequest.GetRequestStream();
            StreamWriter sv = new StreamWriter(stream);
            sv.Write(_ContentLength);
            stream.Write(POSTArray, 0, POSTArray.Length);
            stream.Close();

            //WebResponse webResponse = httpRequest.GetResponse();
            HttpWebResponse webResponse = (HttpWebResponse)httpRequest.GetResponse();
            // Читаем страницу с формой
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            string tmp = "";
            while (sr.Peek() >= 0)
                tmp += sr.ReadLine();
            File.WriteAllText(@"C:\aaa.txt", tmp);
            webResponse.Close();


W!z@rD 15.02.2010 17:51

ужс =\
Авторизация заключается в том чтобы пихнуть кукисы вовремя.

В принципе можно вот так:

Код:

protected override string SendPost(string url, string postData, string referer, bool allowRedirect)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.AllowAutoRedirect = allowRedirect;
            httpWebRequest.Method = "POST";
            httpWebRequest.UserAgent = UserAgent;
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            if (!string.IsNullOrEmpty(Proxy))
            {
                httpWebRequest.Proxy = new WebProxy(Proxy);
            }
            if (!string.IsNullOrEmpty(Cookies))
            {
                httpWebRequest.Headers.Add(HttpRequestHeader.Cookie, Cookies);
            }
            if (!string.IsNullOrEmpty(referer))
            {
                httpWebRequest.Referer = referer;
            }
            var buffer = Encoding.ASCII.GetBytes(postData);
            httpWebRequest.ContentLength = buffer.Length;
            using (var writer = httpWebRequest.GetRequestStream())
            {
                writer.Write(buffer, 0, buffer.Length);
            }
            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                Cookies = string.IsNullOrEmpty(httpWebResponse.Headers["Set-Cookie"]) ? "" : httpWebResponse.Headers["Set-Cookie"];
                using (var stream = httpWebResponse.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream, Encoding.GetEncoding(1251)))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }


FlyBird 15.02.2010 18:19

Ваш код делает все тоже самое, просто вы его в отдельную ф-цию перенесли.
Я же в тестовом режиме пробую получить контент. Затем ф-ция уйдет в dll в красивом виде. Кстати нужно добавить строку иначе работать не будет.
Код:

httpWebRequest.ProtocolVersion = HttpVersion.Version10;
Ваша ф-ция вернула то же что и моя.
Расскажу, я пытаюсь проломиться вот сюда
http://www.voyna-plemyon.ru
У меня ругается на мир. Не верно выбран мир.

W!z@rD 15.02.2010 18:33

user=LOGIN&clear=true&password=PWD&server=ru1

а у вас:
user=LOGIN&password=******&server_select=1

FlyBird 15.02.2010 18:35

Неее... Это тут так. А в коде у меня по человечески.
Именно &server_select=ru1

W!z@rD 15.02.2010 18:47

не обещаю что сделаю, но скиньте в личку учетку, может быть попробую с авторизацией помочь.

FlyBird 15.02.2010 18:57

Письмо отправлено.

W!z@rD 15.02.2010 19:21

Код:

class Program
    {
        private static bool SendPost(string url, string postData)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.AllowAutoRedirect = false;
            httpWebRequest.Method = "POST";
            httpWebRequest.UserAgent = "User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ProtocolVersion = HttpVersion.Version10;
            httpWebRequest.Referer = "http://www.voyna-plemyon.ru/";
            var buffer = Encoding.ASCII.GetBytes(postData);
            httpWebRequest.ContentLength = buffer.Length;
            using (var writer = httpWebRequest.GetRequestStream())
            {
                writer.Write(buffer, 0, buffer.Length);
            }
            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                var location = httpWebResponse.Headers.Get("Location") ?? "";
                return location.IndexOf("server_id=ru1", StringComparison.InvariantCulture) != -1;
            }
        }

        static void Main(string[] args)
        {
            var user = "";
            var pwd = "";

            var b = SendPost("http://www.voyna-plemyon.ru/index.php?action=login", string.Format("user={0}&clear=true&password={1}&server=ru1", user, pwd));
            Console.WriteLine(b);
        }
    }

пропускает.

FEV 15.02.2010 19:28

вместо
Цитата:

httpRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
нужно
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

FlyBird 16.02.2010 10:45

Верхний скрипт возвращает false
Если вставить
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
То результат моего скрипта не меняется.

Похоже, что я из второго части поговорки про лыжи =(


Время: 05:54