如何从WebResponse获取多个Set-Cookie?

时间:2012-09-09 23:21:53

标签: c# cookies httpwebrequest cookiecontainer

我希望收到并存储到CookieContainer个多个Cookie中。 服务器在向我发出一个请求期间发送此代码(我将这一行看作Fiddler):

  

Set-Cookie:ASP.NET_SessionId = fjkfjrfjeijrfjrifj;路径= /;仅Http

     

Set-Cookie:rua-usm = date = 10.09.2012& ptype = 1& ts = 11& id = cvvkmrfmpr44r4rjj;到期=星期五,1999年12月31日至9999 23:59:59 GMT;路径= /

     

Set-Cookie:rua-usm2 = date = 10.09.2012& ptype = 1& ts = 11;到期=星期五,1999年12月31日至9999 23:59:59 GMT;路径= /

     

Set-Cookie:VisitorDone = 1;到期=星期五,1999年12月31日至9999 23:59:59 GMT;路径= /

如您所见,有4个Cookie。但是当我阅读response.Cookies.Count时,我只得到一个:* ASP.NET_SessionId *。

我使用下一个代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some site");
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

我尝试手动解析Set-cookie字段:

string cookiesText = (response as HttpWebResponse).Headers[HttpResponseHeader.SetCookie];
if (!String.IsNullOrEmpty(cookiesText))
{
    CookieCollection cookiesList = GetAllCookiesFromHeader(cookiesText, host);
    if (cookiesList != null)
        _cookieContainer.Add(new Uri(host),cookiesList);
}


    private CookieCollection GetAllCookiesFromHeader(string strHeader, string strHost)
    {
        ArrayList al = new ArrayList();
        CookieCollection cc = new CookieCollection();
        if (strHeader != string.Empty)
        {
            al = ConvertCookieHeaderToArrayList(strHeader);
            cc = ConvertCookieArraysToCookieCollection(al, strHost);
        }
        return cc;
    }

    private ArrayList ConvertCookieHeaderToArrayList(string strCookHeader)
    {
        strCookHeader = strCookHeader.Replace("\r", "");
        strCookHeader = strCookHeader.Replace("\n", "");
        string[] strCookTemp = strCookHeader.Split(',');
        ArrayList al = new ArrayList();
        int i = 0;
        int n = strCookTemp.Length;
        while (i < n)
        {
            if (strCookTemp[i].IndexOf("expires=", StringComparison.OrdinalIgnoreCase) > 0)
            {
                al.Add(strCookTemp[i] + "," + strCookTemp[i + 1]);
                i = i + 1;
            }
            else
            {
                al.Add(strCookTemp[i]);
            }
            i = i + 1;
        }
        return al;
    }

    private CookieCollection ConvertCookieArraysToCookieCollection(ArrayList al, string strHost)
    {
        CookieCollection cc = new CookieCollection();

        int alcount = al.Count;
        string strEachCook;
        string[] strEachCookParts;
        for (int i = 0; i < alcount; i++)
        {
            strEachCook = al[i].ToString();
            strEachCookParts = strEachCook.Split(';');
            int intEachCookPartsCount = strEachCookParts.Length;
            string strCNameAndCValue = string.Empty;
            string strPNameAndPValue = string.Empty;
            string strDNameAndDValue = string.Empty;
            string[] NameValuePairTemp;
            Cookie cookTemp = new Cookie();

            for (int j = 0; j < intEachCookPartsCount; j++)
            {
                if (j == 0)
                {
                    strCNameAndCValue = strEachCookParts[j];
                    if (strCNameAndCValue != string.Empty)
                    {
                        int firstEqual = strCNameAndCValue.IndexOf("=");
                        string firstName = strCNameAndCValue.Substring(0, firstEqual);
                        string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
                        cookTemp.Name = firstName;

                        Encoding iso = Encoding.GetEncoding("utf-8");//may be utf-8
                        allValue = HttpUtility.UrlEncode(allValue, iso);

                        cookTemp.Value = allValue;
                    }
                    continue;
                }
                if (strEachCookParts[j].IndexOf("path", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    strPNameAndPValue = strEachCookParts[j];
                    if (strPNameAndPValue != string.Empty)
                    {
                        NameValuePairTemp = strPNameAndPValue.Split('=');
                        if (NameValuePairTemp[1] != string.Empty)
                        {
                            cookTemp.Path = NameValuePairTemp[1];
                        }
                        else
                        {
                            cookTemp.Path = "/";
                        }
                    }
                    continue;
                }

                if (strEachCookParts[j].IndexOf("domain", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    strPNameAndPValue = strEachCookParts[j];
                    if (strPNameAndPValue != string.Empty)
                    {
                        NameValuePairTemp = strPNameAndPValue.Split('=');

                        if (NameValuePairTemp[1] != string.Empty)
                        {
                            cookTemp.Domain = NameValuePairTemp[1];
                        }
                        else
                        {
                            cookTemp.Domain = strHost;
                        }
                    }
                    continue;
                }
            }

            if (cookTemp.Path == string.Empty)
            {
                cookTemp.Path = "/";
            }
            if (cookTemp.Domain == string.Empty)
            {
                cookTemp.Domain = strHost;
            }
            cc.Add(cookTemp);
        }
        return cc;
    }

但得到了错误:

  

“Cookie的'Domain'='http://xxxx.xxxx'部分无效。”

据我所知,它与Set-Cookie值中的一些非标准字符有关。但是我按HttpUtility.UrlEncode编码所有值!

2 个答案:

答案 0 :(得分:0)

问题在于CookieCollection cookiesList = GetAllCookiesFromHeader(cookiesText, host);行。 host变量不得包含“http://”字符串。

答案 1 :(得分:0)

您还可能希望将另一个IF语句添加到ConvertCookieArraysToCookieCollection方法以获取到期日期。以下内容适合您。

                if (strEachCookParts[j].IndexOf("expires=", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    strPNameAndPValue = strEachCookParts[j];
                    if (strPNameAndPValue != string.Empty)
                    {
                        NameValuePairTemp = strPNameAndPValue.Split('=');
                        if (NameValuePairTemp[1] != string.Empty)
                        {
                            cookTemp.Expires = Convert.ToDateTime(NameValuePairTemp[1]);
                        }
                    }
                    continue;
                }