c# - programmatically form fill and submit login

拈花ヽ惹草 提交于 2019-12-13 03:43:13

问题


Using C# and ASP.NET I want to programmatically fill in values for a web form and then 'POST' those values.

I've seen examples of others using webclient and other classes in posts such as:

How do you programmatically fill in a form and 'POST' a web page?

I am looking to carry out similar functionality - where I automatically post data to a form. In my case I am looking to submit data to simulate a login. I have a couple of questions:

1) Using the Post code in this thread, how can you determine if the Post was a success? We cant really presume a 200 response is a success. It wouldn't necessarily be correct to presume a 302 redirect signifies success either. Is there any sure fire way to determine we are logged on successfully after the post?

2) Do some sites block requests that do not originate from their own domain?


回答1:


yes some sites block request. but you can check the login with auth cookie. Use HttpWebRequest/HttpWebResponse

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));

byte[] data = Encoding.Default.GetBytes("item1=11111&item2=22222&Item3=33333");
request.Method = "POST";
request.ContentLength = data.Length;

Stream sout = request.GetRequestStream();
sout.Write(data, 0, data.Length);
sout.Flush();
sout.Close();

request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

now check response.Cookies for auth cookie



来源:https://stackoverflow.com/questions/27232807/c-sharp-programmatically-form-fill-and-submit-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!