Procedural HttpWebRequest

2019-09-10 19:06发布

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??

1条回答
祖国的老花朵
2楼-- · 2019-09-10 20:04

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("https://example.com/login");
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.

查看更多
登录 后发表回答