例如,如果我将HttpWebRequest
设为“www.sport.com”,我想使用浏览器已存储在之前会话中的Cookie。我怎么能这样做?
更新 也许我没有解释清楚,如果我将httpwebreqeust改为“www.google.com”请求.CookieContainer必须包含chrome / firefox / ie / etc ...已存储在google.com之前所有会话中的所有cookie 。例如在Firefox中我可以看到它们进入选项>隐私>删除单个cookie。
UPDATE2: 我需要这样的东西:
如果我创建像这样的httpwebrequest ,则在JavaScript中
document.write('<script type="text/javascript" src="http://www.google.com"><\/script>')
自动获取已存储在浏览器之前会话中的Cookie
答案 0 :(得分:0)
首先创建HttpWebRequest,设置所有内容,然后向其中添加Cookie,按照link所述进行操作:
1)为HttpWebRequest的HttpWebRequest.CookieContainer属性创建一个System.Net.CookieContainer对象。
request.CookieContainer = new CookieContainer();
2)使用CookieContainer.Add方法将cookie对象添加到HttpWebRequest.CookieContainer。
request.CookieContainer.Add(new Uri("http://api.search.live.net"),new Cookie("id","1234"));
更新:对于您的新评论,访问Cookie非常简单,您可以从HttpContext.Current.Request.Cookies获取它们。
答案 1 :(得分:0)
这是一个使用HttpWebRequest和HttpContext.Current.Request.Cookies对象提供的浏览器cookie的方法。
public static string WebRequestPostRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookieContainer = new CookieContainer();
HttpCookieCollection httpCookies = HttpContext.Current.Request.Cookies;
for (int j = 0; j < httpCookies.Count; j++)
{
HttpCookie httpCookie = httpCookies.Get(j);
Cookie myCookie = new Cookie();
// Convert between the System.Net.Cookie to a System.Web.HttpCookie...
myCookie.Domain = request.RequestUri.Host;
myCookie.Expires = httpCookie.Expires;
myCookie.Name = httpCookie.Name;
myCookie.Path = httpCookie.Path;
myCookie.Secure = httpCookie.Secure;
myCookie.Value = httpCookie.Value;
cookieContainer.Add(myCookie);
}
request.Method = "POST";
//set other request properties here...
var response = (HttpWebResponse)request.GetResponse();
return new StreamReader(response.GetResponseStream()).ReadToEnd();
}