我使用Webclient类,首先使用它来发送Post请求并将登录数据发送到服务器。从这篇文章我想要CookieContainer,但我怎么能得到这个呢? 在此之后,我想向同一服务器发送Get请求,并立即使用Post请求中的CookieContainer。所以我首先要获得cookie,然后我想要设置它。但是它如何与Webclient类一起工作呢?我找到了类似的东西:
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;
}
}
但是使用这个类,我也无法在Get请求中使用Post请求中的CookieContainer。
答案 0 :(得分:0)
你能试试吗
public class CookieAwareWebClient : WebClient
{
private static CookieContainer m_container = null;
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (m_container != null)
{
webRequest.CookieContainer = m_container;// will be called from the second time onwards
}
else
{
webRequest.CookieContainer = new CookieContainer();// First time
m_container = webRequest.CookieContainer; // Copy the container after the post is success
}
return request;
}
}