如何向某网址Post信息,并得到CookieContainer以便以后直接通过验证
发布网友
发布时间:2022-04-24 10:09
我来回答
共1个回答
热心网友
时间:2023-10-09 22:16
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";
//
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);
//再次显示"登录"
//如果把*行注释调,就显示"没有登录"
}