HttpWebRequest采集讀取網站掛載Cookie的通用方法


Asp.net 版本

HttpWebRequest采集時添加:httpWebRequest.CookieContainer = new CookieContainer();就能遠程掛載上cookie,那么怎樣去讀取掛載上的cookie呢?

下面方法為大家解除煩惱。

遍歷方法:

public static List<Cookie> GetAllCookies(CookieContainer cc)
{
    List<Cookie> lstCookies = new List<Cookie>();

    Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
    StringBuilder sb = new StringBuilder();
    foreach (object pathList in table.Values)
    {
        SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
        foreach (CookieCollection colCookies in lstCookieCol.Values)
            foreach (Cookie c in colCookies)
            {
                lstCookies.Add(c);
                sb.AppendLine(c.Domain + ":" + c.Name + "____" + c.Value + "\r\n");
            }
    }
    return lstCookies;
}

使用:

List<Cookie> _cookieList = GetAllCookies(req.CookieContainer);
string _cookieValue = _cookieList[0].ToString();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM