Skip to content

Instantly share code, notes, and snippets.

@jz5
Created June 13, 2015 16:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jz5/fab9e723da0330a47b0a to your computer and use it in GitHub Desktop.
static void Main(string[] args)
{
// ログインして Cookie 取得
var cookies = Login("スクリーンネームまたはメールアドレス", "パスワード");
// 取得した Cookie を付けてアカウント設定ページにアクセス
var url = "https://twitter.com/settings/account";
var req = WebRequest.CreateHttp(new Uri(url));
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookies);
string html = null;
using (var res = req.GetResponse())
{
using (var rs = res.GetResponseStream())
{
using (var sr = new StreamReader(rs))
{
html = sr.ReadToEnd();
}
}
}
}
private static Tuple<string, CookieCollection> GetAuthenticityTokenAndCookies()
{
var req = WebRequest.CreateHttp("https://twitter.com/");
req.Method = "GET";
req.ServicePoint.Expect100Continue = false;
req.CookieContainer = new CookieContainer();
using (var res = req.GetResponse() as HttpWebResponse)
{
string html = null;
using (var rs = res.GetResponseStream())
{
using (var sr = new StreamReader(rs, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
}
html = html.Substring(html.IndexOf("action=\"https://twitter.com/sessions\""));
var m = Regex.Match(html, "value=\"(?<token>.*?)\"\\s+name=\"authenticity_token\"");
return new Tuple<string, CookieCollection>(m.Groups["token"].Value, res.Cookies);
}
}
private static CookieCollection Login(string name, string password)
{
var val = GetAuthenticityTokenAndCookies();
var token = val.Item1;
var cookies = val.Item2;
var param = string.Format("session%5Busername_or_email%5D={0}&session%5Bpassword%5D={1}&remember_me=0&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token={2}", name, password, token);
var buf = System.Text.Encoding.ASCII.GetBytes(param);
var uri = new Uri("https://twitter.com/sessions");
var req = WebRequest.CreateHttp(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buf.Length;
req.Referer = "https://twitter.com/";
req.ServicePoint.Expect100Continue = false;
req.CookieContainer = new CookieContainer();
if (cookies != null)
{
req.CookieContainer.Add(cookies);
}
using (var rs = req.GetRequestStream())
{
rs.Write(buf, 0, buf.Length);
}
string html = null;
using (var res = req.GetResponse())
{
using (var rs = res.GetResponseStream())
{
using (var sr = new StreamReader(rs, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
}
return req.CookieContainer.GetCookies(uri);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment