Reputation: 69
Can you guys help me login into the Twitter (http://twitter.com) with a webrequest?
I have done everything I could think of,
Here is my code (I have replaced my actual username and password for Twitter with USERNAME and PASSWORD):
private void Form1_Load(object sender, EventArgs e)
{
HtmlNode.ElementsFlags.Remove("form");
string url = "https://twitter.com";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
CookieContainer temp = new CookieContainer();
var value = doc.DocumentNode.SelectSingleNode("//input[@type='hidden' and @name='authenticity_token']")
.Attributes["value"].Value;
Console.WriteLine(value);
HttpWebRequest req =(HttpWebRequest) WebRequest.Create("https://twitter.com/sessions");
req.Method = "POST";
string postData = "session%5Busername_or_email%5D=USERNAME&session%5Bpassword%5D=PASSWORD&remember_me=1&return_to_ssl=false&scribe_log=&redirect_after_login=%2F&authenticity_token=" + value.Trim();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = new CookieContainer();
// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.Referer = "https://twitter.com/sessions";
req.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36";
req.ContentLength = byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = req.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
Upvotes: 0
Views: 96
Reputation: 70218
Instead of scraping web pages directly, you should rather use the Twitter API. There are some .NET libraries available.
Upvotes: 2