How to call a SSL web page programmatically
Published Nov 16 2018 06:56 AM 196 Views
Microsoft
First published on MSDN on Jan 16, 2014

Not all days are equal. Recently, my day was challenged with a fun but daunting task: to assist a customer to write some C# code to call a https webpage programmatically. Here is what we ended up coding the login page:


Note: Since every site is different, you will need to collect Fiddler trace to intercept the form data and code them accordingly


public partial class Form1 : Form


{
CookieContainer cookieJar = null;


public Form1()
{
InitializeComponent();
cookieJar = new CookieContainer();
}


private void button1_Click(object sender, EventArgs e)
{
//POST form data to authenticate the session
MakeHttpCall("POST"," https://www.mysite.com/login ");


}


private void MakeHttpCall(string method, string uri)
{
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);
webReq.CookieContainer = cookieJar;
webReq.Method = method;


if(method == "POST"){
//have to set the POST data content type
webReq.ContentType = "application/x-www-form-urlencoded";


//collect the formData from Fiddler trace
string formData =@"utf8=%E2%9C%93&authenticity_token=%2AAbgakfjdADFOEIRbereoidfnfidfjdfj%2Fb0IeGZRMGqjnw%3D&use... ";
webReq.Referer = " https://www.mysite.com/ ";
// we need to store the data into a byte array. Content will be what server looking for
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(formData);
webReq.ContentLength = PostData.Length;
Stream tempStream = webReq.GetRequestStream();
// write the data to be posted to the Request Stream
tempStream.Write(PostData,0,PostData.Length);
tempStream.Close();


}


//Get the response from the server
HttpWebResponse webResp = (HttpWebResponse) webReq.GetResponse();
StreamReader sr = new StreamReader(webResp.GetResponseStream(), Encoding.ASCII);
//put the stream data in a string
String respData = sr.ReadToEnd();
sr.Close();
webResp.Close();


if (method == "POST")
{
MessageBox.Show(respData.ToString());
}
}
}

Version history
Last update:
‎Nov 16 2018 06:56 AM
Updated by: