【懂Cookies保持的老鸟请进】——话说HttpWebRequest,HttpWebResponse中怎样梅开二度,再续前缘。
在WinFrom的HttpWebRequest或Respone中,
可以利用: CookieContainer 来保存Cookie,让后续的页面继续使用保存下来的Cookie,如:
/// <summary>
/// 解析Cookie
/// </summary>
/// <param name="response"></param>
private void ParseCookie(HttpWebResponse response)
{
if (!IgnoreCookies)
{
string cookiesExpression = response.Headers["Set-Cookie"];
if (!string.IsNullOrEmpty(cookiesExpression))
{
Uri cookieUrl = new Uri(string.Format("{0}://{1}:{2}/",
response.ResponseUri.Scheme,
response.ResponseUri.Host,
response.ResponseUri.Port));
_cookieContainer.SetCookies(cookieUrl, cookiesExpression);
}
}
}
/// <summary>
/// 配置请求设置
/// </summary>
/// <param name="request"></param>
private void ConfigRequest(HttpWebRequest request)
{
request.UserAgent = UserAgent;
request.Referer= "";
request.CookieContainer = _cookieContainer;
request.AllowAutoRedirect =AllowAutoRedirect;
request.MediaType = "text/html";
request.Headers["Accept-Language"] = "zh-CN,zh;q=0.8";
if (Timeout > 0)
request.Timeout = Timeout;
}