How to get multiple Set-Cookie from WebResponse?

故事扮演 提交于 2019-12-10 19:20:59

问题


I want to receive and store into CookieContainer multiple cookies. Server send this code during one request to me (I see this lines into Fiddler):

Set-Cookie: ASP.NET_SessionId=fjkfjrfjeijrfjrifj; path=/; HttpOnly

Set-Cookie: rua-usm=date=10.09.2012&ptype=1&ts=11&id=cvvkmrfmpr44r4rjj; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/

Set-Cookie: rua-usm2=date=10.09.2012&ptype=1&ts=11; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/

Set-Cookie: VisitorDone=1; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/

as you see there are 4 cookies. But when I read response.Cookies.Count I get only one: *ASP.NET_SessionId*.

I use next code :

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

I tried parse Set-cookie field manually:

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;
    }

But got error:

"The 'Domain'='http://xxxx.xxxx' part of the cookie is invalid."

As I understand it related to some not standart characters into Set-Cookie value. But I encoded all values by HttpUtility.UrlEncode!


回答1:


Problem was with CookieCollection cookiesList = GetAllCookiesFromHeader(cookiesText, host); line. host variable must not contains "http://" string.




回答2:


You also may want to add another IF statement to the ConvertCookieArraysToCookieCollection method to get the expiration date as well. The following should work for you.

                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;
                }


来源:https://stackoverflow.com/questions/12343789/how-to-get-multiple-set-cookie-from-webresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!