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

来源:互联网 发布:淘宝佣金插件 编辑:程序博客网 时间:2024/06/05 02:32
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
原创粉丝点击