专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »DotNet » httpwebrequest:通过HttpWebRequest 发送 POST 请求实现自动登陆 »正文

httpwebrequest:通过HttpWebRequest 发送 POST 请求实现自动登陆

来源: 发布时间:星期六, 2008年12月13日 浏览:74次 评论:0
怎样通过HttpWebRequest 发送 POST 请求到个网页服务器?例如编写个实现自动用户登录自动提交表单数据到网站等
假如某个页面有个如下表单(Form):view plaincopy to clipboardpr?
<form name="form1" action="http:www.n.com/login.asp" method="post">
<input type="text" name="userid" value="">
<input type="password" name="password" value="">
</form>

<form name="form1" action="http:www.n.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#写提交:view plaincopy to clipboardpr?
strId = "guest";
strPassword= "123456";

ASCIIEncoding encoding= ASCIIEncoding;
postData="userid="+strId;
postData ("&password="+strPassword);

data = encoding.GetBytes(postData);

// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http:www.here.com/login.asp");

myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream Stream=myRequest.GetRequestStream;

// Send the data.
Stream.Write(data,0,data.Length);
Stream.Close;

// Get response
HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse;
StreamReader reader = StreamReader(response.GetResponseStream,Encoding.Default);
content = reader.ReadToEnd;
Console.WriteLine(content);

0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: