winform保存登录cookie

 
 在web程序中,我们通常使会使用cookie来保存一些用户状态,或者权限或者你想保存的东西,但是在CS程序中,如果要使用cookie就必须要做些功课了。。。

最好注意以下几点:
   1.使用成员变量:CookieContainer mycookie=new CookieContainer(); 
   2.在每个HttpWebRequest创建后赋值 CookieContainer 属性 request.CookieContainer = mycookie;
   3.在每次创建响应HttpWebResponse时将cookie的内容重新写回请求中 
                                                               response.Cookies = mycookie.GetCookies(request.RequestUri);
   
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace APPTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
       // private const string baseUrl = "";
        private CookieContainer mycookie=new CookieContainer();
        private CookieCollection cookieCollection = new CookieCollection();     
        private void Form1_Load(object sender, EventArgs e)
        {
            txtbaseUrl.Text = "http://passport.baidu.com/center";
            txtparams.Text = "{\"loginname\":\"...\",\"loginpwd\":\"...\"}";
            txtType.Text = "Post";
            /*
            uuid:db1921de-421b-4f8d-8ca4-664c7cfcd0c7
            loginname:1234
            nloginpwd:123
            loginpwd:123
            machineNet:
            machineCpu:
            machineDisk:
            authcode:mfcv
            dAsFXMIFRN:fDFLH
             */
        }

   

        private void btnOK_Click(object sender, EventArgs e)
        {
            mydata data = new mydata { url=txtUrl.Text, param=txtparams.Text, type=txtType.Text };
            if (data.type.ToUpper()=="GET")
            {
                richTextBox1.Text = GetDataWithMyClass(data);
            }else{
                richTextBox1.Text = PostDataWithMyClass(data);
            }
           
            
        }

        private string GetDataWithMyClass(mydata data)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("{0}{1}/{2}",txtbaseUrl.Text,data.url,data.param));
            request.CookieContainer = mycookie;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            
            string ret = string.Empty;
            Stream s;          
            string strValue = "";

            if (response.StatusCode == HttpStatusCode.OK)
            {
                response.Cookies = mycookie.GetCookies(request.RequestUri);
                s = response.GetResponseStream();             
                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                strValue = Reader.ReadToEnd();
                Reader.Close();
            }
            return strValue;
        }
     
        private string PostDataWithMyClass(mydata data)
        {                
           
            // 将提交的字符串数据转换成字节数组 
            byte[] postData = Encoding.UTF8.GetBytes(data.param);

            // 设置提交的相关参数 
            HttpWebRequest request = WebRequest.Create(string.Format("{0}{1}", txtbaseUrl.Text, data.url)) as HttpWebRequest;         
            request.Method = data.type;
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;
            request.ContentType = "application/x-www-form-urlencoded";
           // request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.CookieContainer = mycookie;
            request.ContentLength = postData.Length;

            // 提交请求数据 
            System.IO.Stream outputStream = request.GetRequestStream();
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();

            HttpWebResponse response;
            Stream responseStream;
            StreamReader reader;
            string srcString;
            try
            {
                response = request.GetResponse() as HttpWebResponse;
                response.Cookies = mycookie.GetCookies(request.RequestUri);
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);                
                srcString = reader.ReadToEnd();
                cookieCollection = response.Cookies;
                reader.Close();
                return srcString;
            }
            catch (Exception e)
            {  
                MessageBox.Show(e.Message,"错误", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            return "";           
           
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                txtbaseUrl.Text = "http://passport.baidu.com/center";
                txtparams.Text = "{\"loginname\":\"\",\"loginpwd\":\"\"}";
                txtType.Text = "Post";
            }
            else {
                txtbaseUrl.Text = "http://jd2008.jd.com/JdHome/OrderList.aspx";
                txtparams.Text = "";
                txtType.Text = "Get";
            }
            
        }
 }
    public class mydata
    {
        public string remark { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string param { get; set; }
        public string type { get; set; }
    }
}

  

转载于:https://www.cnblogs.com/unintersky/p/3880036.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值