Авторизация на сайте. POST - запрос - C#
Формулировка задачи:
Миллион тем было, миллион тем будет.
Ниже процедура и 2 вызова.
для LDS - работает, для Life - получаю в response - 403 Forbidden.
Из-за id_msisdn_code (063/073/093) POST-запрос меняется, но как меняется?
И какие параметры брать для передачи, которые подписаны name? (msisdn и super_password соответственно)
Есть у кого-то предложения по этому поводу?
Вызов 1(работает):
Вызов 2(не работает):
Исходный код страницы 1 вызова(урезан до нужной части).
Исходный код страницы 2 вызова(урезан до нужной части):
Впихнул их в запрос: String secondStepForm3 = cookie+login_style+login+pass_style+pass;
Итог один - Forbidden 403. Сдаюсь и надеюсь на помощь форума.
static string CheckBySite(string site_name, string login,
string pass, string login_style,
string pass_style, string wordtofind,
string companyname,int afterword, int count)
{
String secondStepForm3 = login_style+login+pass_style+pass;
HttpWebRequest request3 = (HttpWebRequest)WebRequest.Create(site_name);
request3.UserAgent = ".NET Framework Test Client";// "Opera/9.80";
request3.Method = "POST";
request3.ContentType = "application/x-www-form-urlencoded";
byte[] EncodedPostParams3 = Encoding.Default.GetBytes(secondStepForm3);
request3.ContentLength = EncodedPostParams3.Length;
request3.GetRequestStream().Write(EncodedPostParams3, 0, EncodedPostParams3.Length);
request3.GetRequestStream().Close();
HttpWebResponse response = (HttpWebResponse)request3.GetResponse();
string lol = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("KOI8-R")).ReadToEnd();
int pos = lol.IndexOf(wordtofind); //если слово "Баланс есть на странице - мы авторизовались".
if (pos != -1)
{
string test = lol.Substring(pos + afterword, count); //грубо говоря получили 6-значное число. Если упадёт до 5 значного заберёт одну кавычку.
test = test.Replace('.', ','); //заменим точку на запятую для работы с числами.
double numVal = Double.Parse(test) / 2; // для перевода в гривны делим на 2.
lol = companyname + ": " + numVal.ToString() + " грн.";
}
else
lol = companyname + " :Something wrong with site!";
return lol;
}string lds_site = "https://stat.lds.net.ua";
string lds_login = "login";
string lds_pass = "pass";
string lds_login_style = "username=";
string lds_pass_style = "&userpass=";
string lds_word_to_find = "Баланс";
int lds_after_word_sym = 277;
int lds_balans_length = 6;
lds_result = CheckBySite(lds_site, lds_login, lds_pass,lds_login_style,lds_pass_style,lds_word_to_find, "LDS",lds_after_word_sym,lds_balans_length);tring life_site = "https://my.life.ua/ru/";
string life_login = "number";
string life_pass = "password";
string life_login_style = "id_msisdn_code=063&id_msisdn="; //суть здесь
string life_pass_style = "&super_password=";
string life_word_to_find = "07.11.2014"; // дата регистрации, пофиг
int life_after_word_sym = 277;
int life_balans_length = 7;
life_result = CheckBySite(life_site, life_login,
life_pass, life_login_style,
life_pass_style, life_word_to_find, "LIFE",
life_after_word_sym, life_balans_length);<tr><td class="form-legend-auth">Логин или лицевой счет</td><td><input type="text" name="username" id="username" value="" style="width:150px" class="nt-input"></td></tr>
<tr><td class="form-legend-auth">Ваш пароль</td><td><input type="password" name="userpass" id="userpass" style="width:150px" class="nt-input"></td></tr>
<td>Введите ваш номер:</td>
<td>
<div class="phone-section">
<select id="id_msisdn_code" name="msisdn_code" class="phone-select">
<option value="063" >063</option>
<option value="073" >073</option>
<option value="093" >093</option>
</select>
<input autocomplete="off" name="msisdn" maxlength="7" type="text" class="needValid" id="id_msisdn" />
</div>
</td>
</tr>
<tr>
<td><label for="id_super_password">Введите Суперпароль:</label></td>
<td>
<div class="passwoard-section">
<input id="id_super_password" type="password" class="needValid noText-valid min6 password-valid" name="super_password" maxlength="6" />
<a href="javascript:void(0);" class="info-link">
Параметры(2 вызов):
csrfmiddlewaretoken:"uRBEi8SbII2CSzVXMfPSIN7UiOALrovS"
msisdn_code:"063"
msisdn:"3335566"
super_password:"879645"
Ответ 2 вызов:
<td>Введите ваш номер:</td>
<td>
<div class="phone-section">
<select id="id_msisdn_code" name="msisdn_code" class="phone-select">
<
option value="063" selected="selected">063
</option> <option value="073" >073</option> <option value="093" >093</option> </select> <input autocomplete="off" name="msisdn" maxlength="7" type="text" class="needValid" value="3335566" id="id_msisdn" /> </div> </td> </tr> <tr> <td><label for="id_super_password">Введите Суперпароль:</label></td> <td> <div class="passwoard-section"> <input name="super_password" value="879645" class="needValid noText-valid min6 password-valid" maxlength="6" type="password" id="id_super_password" /> <a href="javascript:void(0);" class="info-link"> <span class="info-sub"> <span class="hidden-icon"> </span> Получить СуперПароль можно, отправив SMS с текстом PAROL на номер 123 </span> </a> </div> </td> </tr>
============================================================================
Финал:
Form Data(view parced):
Для 1 случая: username=23423423&userpass=123iop
Для 2 случая: csrfmiddlewaretoken=9fJjZkCexnx27y9v34paW7dLRP1IXS2o&msisdn_code=063&msisdn=3452312&super_password=434353
Сие чудо берётся с Куки:
Cookie:csrftoken=9fJjZkCexnx27y9v34paW7dLRP1IXS2o; mylifeua-sessionid=f00a5e94ebae799253e58b9486677d21; __utmt=1; __utma=203133709.416984635.1446028403.1446028403.1446030470.2; __utmb=203133709.1.10.1446030470; __utmc=203133709; __utmz=203133709.1446028403.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Вопросы по ходу дела меняются:
Как симитировать Куки или где они получаются?
Ну и финал этого всего:
Получил куки с помощью этого:
static string GetCookie( string site)
{
string url = site;
HttpWebRequest tQ = (HttpWebRequest)HttpWebRequest.Create(url);
tQ.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
tQ.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0";
tQ.ContentType = "application/x-www-form-urlencoded";
tQ.Referer = url;
HttpWebResponse tS = (HttpWebResponse)tQ.GetResponse();
string tC = tS.Headers["Set-Cookie"];
Console.WriteLine(tC);
tS.Close();
return tC;
}
Жаль, наверное, слишком много букаф
Решение задачи: «Авторизация на сайте. POST - запрос»
textual
Листинг программы
static CookieContainer cc = new CookieContainer();
static string[] cooks = new string[15];
static string UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:42.0) Gecko/20100101 Firefox/42.0";
static string host = "my.life.ua";
static string Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
static string AcceptLanguage = "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3";
static string Encod = "gzip, deflate";
static string Referer = "https://my.life.ua/ru/";
static string ContentType = "application/x-www-form-urlencoded";
static double SendRequest(string site, string method)
{
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(site);
wreq.Accept = Accept;
wreq.UserAgent = UserAgent;
wreq.Method = method;
wreq.CookieContainer = cc;
wreq.Headers.Add("Accept-Language", AcceptLanguage);
wreq.Headers.Add("Accept-Encoding", Encod);
wreq.KeepAlive = true;
if (method == "POST")
{
wreq.Referer = Referer;
wreq.ContentType = ContentType;
wreq.Host = host;
string POST_Request = "csrfmiddlewaretoken=" + cooks[0] + "&msisdn_code=063&msisdn=login&super_password=pass";
byte[] EncodedPostParams3 = Encoding.UTF8.GetBytes(POST_Request);
wreq.ContentLength = EncodedPostParams3.Length;
wreq.GetRequestStream().Write(EncodedPostParams3, 0, EncodedPostParams3.Length);
wreq.GetRequestStream().Close();
HttpWebResponse wres = (HttpWebResponse)wreq.GetResponse();
string html = "";
if (wres.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(wres.GetResponseStream(),Encoding.UTF8))
{
html += reader.ReadToEnd();
html = Regex.Replace(html, "<[^>]+>", string.Empty);
html = html.Replace(" ", string.Empty);
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
html = rgx.Replace(html, replacement);
int pos = html.IndexOf("07.11.2014");
if (pos != -1)
html = html.Substring(pos + 11, 6);
else
html = "Error";
Console.WriteLine(html);
}
Console.ReadLine();
}
else if (wres.StatusCode == HttpStatusCode.Forbidden)
{
//CheckByModem(life_pnum);
return 0;
}
}
else
{
HttpWebResponse wres = (HttpWebResponse)wreq.GetResponse();
int i = 0;
if (wres.Cookies.Count > 1)
{
foreach (Cookie cook in wres.Cookies)
{
cooks[i] += cook.Value;
i++;
}
}
else cooks[1] = wres.Cookies.ToString();
}
return 0;
}
static void Main(string[] args)
{
string site = "https://my.life.ua/ru/";
SendRequest(site, "GET");
SendRequest(site, "POST");
}
}