Dove Devic Dove Devic - 1 year ago 53
C# Question

Procedural HttpWebRequest

So I will start by saying I am very new and basic when it comes to HttpWebRequesting. I have a scheduler that I want to automate. But in order for me to do so, I have to do all of the following, in this order:

1) enter Username and Password

1a)Hit Login

2) Select radio button with "2016" text

2a)Hit Continue

3) reenter password

3a) Hit OK

4) enter schedule ID

4a) hit Add

After all this the website usually displays a green or red label at the top of the screen representing whether the item was scheduled right or not. At the moment, I have all this working with the WebBrowser Control, and I am scraping off all the Elements and Attributes for each item to check to see if it is the proper field to enter data into. However, I have been recently told that using HttpRequests would be much much much faster.

After researching around some, I came across this for authentication. Am I on the right track??

Any suggestions or hints??

Answer Source

You should open your browser network monitor see whats the method the request have used what's the name of the passed parametres and simulate that in your HttpWebRequest object, i assume you already know how to do GET method, here is how you do a basic POST request with HttpWebRequest

var cookies = new CookieContainer();
var req = (HttpWebRequest)WebRequest.Create("");
req.CookieContainer = cookies; 
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

var buffer = Encoding.UTF8.GetBytes("user=foo&pass=bar"); //passed params
req.ContentLength = buffer.Length;
using (var reqStream = req.GetRequestStream()) {
      reqStream.Write(buffer, 0, buffer.Length);

using (var res = req.GetResponse())
using (var resStream = res.GetResponseStream())
using (var reader = new StreamReader(resStream)) {
       var respStr = reader.ReadToEnd();

and you should use the same CookieContainer object for all requests, respStr is now the server text response, you may also send additional headers within the request (use req.Headers.AddHeader() if needed), or set the user-agent or change the content-type, etc that depends on what you find in the network monitor or you may use a desktop application like fiddler.