首页  ·  知识 ·  编程语言
向某网址Post信息,并得到CookieContainer以便以后直接通过验证
goody9807  http://www.cnblogs.com/goody9807  .NET  编辑:dezai  图片来源:网络
using system;using system.net;using system.io;using system.text;[stathread]static void main(string[] args){

 
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);
//再次显示"登录"
//如果把*行注释调,就显示"没有登录"
}

 

本文作者:goody9807 来源:http://www.cnblogs.com/goody9807
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读