您的位置:首页 > 大数据 > 人工智能

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

2017-05-24 17:55 671 查看
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;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐