CookieContainer模拟登陆存储Cookie以便二次登录用

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Default2 : System.Web.UI.Page
{


    private static CookieContainer m_Cookie = new CookieContainer(); //记录浏览器session




    protected void Page_Load(object sender, EventArgs e)
    {
        string strUrl = "http://xxx:8083/Api/login";


        string json = "";
        json = SendPostHttpRequest(strUrl, "application/x-www-form-urlencoded", "account=admin&password=admin");


        string s1 = json;


        strUrl = "http://xxx:8083/Api/getHistoryLast";


        json = SendPostHttpRequest(strUrl, "application/x-www-form-urlencoded", "type=0&strTEID=64844962885&jsession=cfcd208495d565ef66e7dff9f98764da");


        string s2 = json;




    }


    /// <summary>
    /// 发送请求
    /// </summary>
    /// <param name="url">Url地址</param>
    /// <param name="method">方法(post或get)</param>
    /// <param name="method">数据类型</param>
    /// <param name="requestData">数据</param>
    public string SendPostHttpRequest(string url, string contentType, string requestData)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        if (m_Cookie != null)
        {
            request.CookieContainer = m_Cookie;
        }


        request.Method = "POST";
        byte[] postBytes = null;
        request.ContentType = contentType;
        postBytes = Encoding.UTF8.GetBytes(requestData);
        request.ContentLength = postBytes.Length;
        using (Stream outstream = request.GetRequestStream())
        {
            outstream.Write(postBytes, 0, postBytes.Length);
        }
        string result = string.Empty;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            if (m_Cookie == null)
            {
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                CookieCollection cook;
                cook = response.Cookies;
                m_Cookie.Add(cook);
            }


            if (response != null)
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        return result;
    }








}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值