【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 1824|回复: 0

HttpWebRequest模拟登陆,存储Cookie以便登录请求后使用

[复制链接]
发表于 2014-3-19 11:00:21 | 显示全部楼层 |阅读模式
[mw_shl_code=csharp,true]public static string PostLogin(string postData, string requestUrlString, ref CookieContainer cookie)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(postData);
        //向服务端请求
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.ContentLength = data.Length;
        myRequest.CookieContainer = new CookieContainer();
        Stream newStream = myRequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        //将请求的结果发送给客户端(界面、应用)
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        cookie.Add(myResponse.Cookies);
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        return reader.ReadToEnd();
    }[/mw_shl_code]
PostRequest :登录后使用Cookie进行其他操作[mw_shl_code=csharp,true]public static string PostRequest(string postData, string requestUrlString, CookieContainer cookie)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(postData);
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";        
        myRequest.ContentLength = data.Length;
        myRequest.CookieContainer = cookie;
        Stream newStream = myRequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        return reader.ReadToEnd();
    }[/mw_shl_code]e.g.
[mw_shl_code=csharp,true]string strIMSPhone = tb_IMSPhone.Text.Trim();
            string strIMSPwd = tb_IMSPwd.Text.Trim();
            string postData = "username=" + strIMSPhone + "&password=" + strIMSPwd + "&type=2";
            CookieContainer cookie=new CookieContainer();
            if (IMSHelper.PostLogin(postData, post_signIn, ref cookie).Equals("ok"))
            {
                string strCont = PostRequest("", post_getContJsonData, cookie);   
            }[/mw_shl_code]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-5-15 00:21

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表