I am trying to log in to instagram using web requests. I am having a bad time understanding what's going on. Getting this: The remote server returned an error: (403) Forbidden. What I have so far:
public static string csrf;
CookieContainer c1 = new CookieContainer();
private void button1_Click(object sender, EventArgs e)
{
string PostData = String.Format("csrfmiddlewaretoken={0}&username=ra123&password=ra12345678",getToken());
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://instagram.com/accounts/login/");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = true;
req.AllowAutoRedirect = true;
req.CookieContainer = c1;
byte[] byteArray = Encoding.ASCII.GetBytes(PostData);
req.ContentLength = byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
HttpWebResponse webResp = (HttpWebResponse)req.GetResponse();
Stream datastream = webResp.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
string s = reader.ReadToEnd();
MessageBox.Show(s);
if (s.Contains("ra123"))
{
MessageBox.Show("Loggedin");
}
else
{
MessageBox.Show("Not");
}
}
string getToken()
{
string p = "<input type="hidden" name="csrfmiddlewaretoken" value="(.*)"/>";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://instagram.com/accounts/login/");
req.Method = "GET";
req.CookieContainer = c1;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream data = resp.GetResponseStream();
StreamReader sr = new StreamReader(data);
string src = sr.ReadToEnd();
Match m = Regex.Match(src, p);
if (m.Success)
{
return (m.Groups[1].Value.ToString());
}
return false.ToString();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…