(论坛答疑点滴)如果向某网址Post信息,并得到CookieContainer以便以后直接通过验证
2024-07-21 02:15:59
供稿:网友
,欢迎访问网页设计爱好者web开发。using system;
using system.net;
using system.io;
using system.text; [stathread]
static void main(string[] args)
{
//
// todo: 在此处添加代码以启动应用程序
//
string url="http://localhost/csdn2/1.asp";
// <%
// if request("aa")="zhuye" then session("ok")="ok"
// if session("ok")="ok" then
// response.write("登录")
// else
// response.write("没有登录")
// end if
// %>
string indata="aa=zhuye";
string outdata="";
cookiecontainer mycookiecontainer=new cookiecontainer();
//新建一个cookiecontainer来存放cookie集合
httpwebrequest myhttpwebrequest=(httpwebrequest)webrequest.create(url);
//新建一个httpwebrequest
myhttpwebrequest.contenttype="application/x-www-form-urlencoded";
myhttpwebrequest.contentlength=indata.length;
myhttpwebrequest.method="post";
myhttpwebrequest.cookiecontainer=mycookiecontainer;
//设置httpwebrequest的cookiecontainer为刚才建立的那个mycookiecontainer
stream myrequeststream=myhttpwebrequest.getrequeststream();
streamwriter mystreamwriter=new streamwriter(myrequeststream,encoding.getencoding("gb2312"));
mystreamwriter.write(indata);
//把数据写入httpwebrequest的request流
mystreamwriter.close();
myrequeststream.close();
//关闭打开对象
httpwebresponse myhttpwebresponse=(httpwebresponse)myhttpwebrequest.getresponse();
//新建一个httpwebresponse
myhttpwebresponse.cookies=mycookiecontainer.getcookies(myhttpwebrequest.requesturi);
//获取一个包含url的cookie集合的cookiecollection
stream myresponsestream=myhttpwebresponse.getresponsestream();
streamreader mystreamreader=new streamreader(myresponsestream,encoding.getencoding("gb2312"));
outdata=mystreamreader.readtoend();
//把数据从httpwebresponse的response流中读出
mystreamreader.close();
myresponsestream.close();
console.writeline(outdata);
//显示"登录"
//拿到了cookie,再进行请求就能直接读取到登录后的内容了
myhttpwebrequest=(httpwebrequest)webrequest.create(url);
myhttpwebrequest.cookiecontainer=mycookiecontainer;//*
//刚才那个cookiecontainer已经存有了cookie,把它附加到httpwebrequest中则能直接通过验证
myhttpwebresponse=(httpwebresponse)myhttpwebrequest.getresponse();
myhttpwebresponse.cookies=mycookiecontainer.getcookies(myhttpwebrequest.requesturi);
myresponsestream=myhttpwebresponse.getresponsestream();
mystreamreader=new streamreader(myresponsestream,encoding.getencoding("gb2312"));
outdata=mystreamreader.readtoend();
mystreamreader.close();
myresponsestream.close();
console.writeline(outdata);
//再次显示"登录"
//如果把*行注释调,就显示"没有登录"
}