首页 > Windows开发 > 详细

C#实现通过HttpWebRequest发送POST请求实现网站自动登陆

时间:2019-07-18 09:38:16      阅读:97      评论:0      收藏:0      [点我收藏+]

C#实现通过HttpWebRequest发送POST请求实现网站自动登陆


怎样通过HttpWebRequest 发送 POST 请求到一个网页服务器?例如编写个程序实现自动用户登录,自动提交表单数据到网站等。
技术分享图片假如某个页面有个如下的表单(Form): 
技术分享图片
技术分享图片<form name="form1" action="http://www.sina.com/login.asp" method="post">
技术分享图片<input type="text" name="userid" value="">
技术分享图片<input type="password" name="password" value="">
技术分享图片</form> 
技术分享图片
技术分享图片从表单可看到表单有两个表单域,一个是userid另一个是password,所以以POST形式提交的数据应该包含有这两项。
技术分享图片其中POST的数据格式为:
技术分享图片表单域名称1=值1&表单域名称2=值2&表单域名称3=值3……
技术分享图片要注意的是“值”必须是经过HTMLEncode的,即不能包含“<>=&”这些符号。
技术分享图片
技术分享图片本例子要提交的数据应该是:
技术分享图片userid=value1&password=value2
技术分享图片
技术分享图片用C#写提交程序:
技术分享图片string strId = "guest";
技术分享图片string strPassword= "123456";
技术分享图片
技术分享图片ASCIIEncoding encoding=new ASCIIEncoding();
技术分享图片string postData="userid="+strId;
技术分享图片postData += ("&password="+strPassword);
技术分享图片
技术分享图片byte[] data = encoding.GetBytes(postData);
技术分享图片
技术分享图片// Prepare web request技术分享图片
技术分享图片HttpWebRequest myRequest =
技术分享图片(HttpWebRequest)WebRequest.Create("http://www.sina.com/login.asp");
技术分享图片
技术分享图片myRequest.Method = "POST";
技术分享图片myRequest.ContentType="application/x-www-form-urlencoded";
技术分享图片myRequest.ContentLength = data.Length;
技术分享图片Stream newStream=myRequest.GetRequestStream();
技术分享图片
技术分享图片// Send the data.
技术分享图片newStream.Write(data,0,data.Length);
技术分享图片newStream.Close();
技术分享图片
技术分享图片// Get response
技术分享图片HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
技术分享图片StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
技术分享图片string content = reader.ReadToEnd();
技术分享图片Response.Write(content); 

 

此方法核心问题是要找到请求页和表单域中的参数ID。

 

 

C#实现通过HttpWebRequest发送POST请求实现网站自动登陆

原文:https://www.cnblogs.com/hbtmwangjin/p/11204586.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!