How to add cookies to WebRequest?

前端 未结 4 2003
刺人心
刺人心 2020-11-29 04:55

I am trying to unit test some code, and I need to to replace this:

  HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create( uri );
  httpWebReque         


        
4条回答
  •  没有蜡笔的小新
    2020-11-29 05:57

    dlev's answer ended up working, but I had problems implementing the solution ("The parameter '{0}' cannot be an empty string."), so I decided to write the full code in case anybody else has similar problems.

    My goal was to get the html as a string, but I needed to add the cookies to the web request. This is the function that downloads the string using the cookies:

    public static string DownloadString(string url, Encoding encoding, IDictionary cookieNameValues)
    {
        using (var webClient = new WebClient())
        {
            var uri = new Uri(url);
            var webRequest = WebRequest.Create(uri);
            foreach(var nameValue in cookieNameValues)
            {
                webRequest.TryAddCookie(new Cookie(nameValue.Key, nameValue.Value, "/", uri.Host));
            }                
            var response = webRequest.GetResponse();
            var receiveStream = response.GetResponseStream();
            var readStream = new StreamReader(receiveStream, encoding);
            var htmlCode = readStream.ReadToEnd();                
            return htmlCode;
        }
    }   
    

    We are using the code from dlev's answer:

    public static bool TryAddCookie(this WebRequest webRequest, Cookie cookie)
    {
        HttpWebRequest httpRequest = webRequest as HttpWebRequest;
        if (httpRequest == null)
        {
            return false;
        }
    
        if (httpRequest.CookieContainer == null)
        {
            httpRequest.CookieContainer = new CookieContainer();
        }
    
        httpRequest.CookieContainer.Add(cookie);
        return true;
    }
    

    This is how you use the full code:

    var cookieNameValues = new Dictionary();
    cookieNameValues.Add("varName", "varValue");
    var htmlResult = DownloadString(url, Encoding.UTF8, cookieNameValues);
    

提交回复
热议问题