相关疑难解决方法(0)

将CookieContainer与WebClient类一起使用

我之前使用过带有HttpWebRequest和HttpWebResponse会话的CookieContainer,但现在,我想将它与WebClient一起使用.据我所知,没有像HttpWebRequests(request.CookieContainer)那样的内置方法.如何从CookieContainer中的WebClient收集cookie?

我用Google搜索并找到以下示例:

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是最好的方法吗?

c# cookies webclient httpwebrequest cookiecontainer

142
推荐指数
5
解决办法
13万
查看次数

尽管Set-Cookie Header(无重定向),HttpWebResponse.Cookies为空

我在努力弄清楚这里有什么问题.我正在发送登录信息,我可以在Header中看到具有正确值的Set-Cookie,但Cookies集合没有被填满.

这是HTTPS,登录自动重定向,但我使用AllowAutoRedirect = false禁用它以尝试解决此问题.

在此屏幕截图中,您可以轻松查看调试信息,并且应该设置cookie.我将我的httpWebRequest.Cookie设置为新的CookieCollection.

右键单击并选择查看图像以查看完整大小.

HttpWebRequest httpRequest;
CookieContainer reqCookies = new CookieContainer();
string url = "https://example.com";
string[] email = user.Split('@');
email[0] = System.Web.HttpUtility.UrlEncode(email[0]);
user = email[0] + "@" + email[1];
pass = System.Web.HttpUtility.UrlEncode(pass);

string postData = "email=" + user + "&password=" + pass;
byte[] byteData = Encoding.UTF8.GetBytes(postData);

httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Referer = url;
httpRequest.CookieContainer = reqCookies;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1003.1 Safari/535.19";
httpRequest.Accept = "text/html, application/xhtml+xml, */*";
httpRequest.ContentType = "application/x-www-form-urlencoded"; …
Run Code Online (Sandbox Code Playgroud)

c# cookies httpwebrequest

24
推荐指数
5
解决办法
4万
查看次数

标签 统计

c# ×2

cookies ×2

httpwebrequest ×2

cookiecontainer ×1

webclient ×1