我正在构建一个应用程序,在用户登录我的网站后,该应用程序会转到一个链接以获取他的用户名,以便我可以在该应用程序上识别他。
现在,如果我作为用户从浏览器登录,然后将类似内容粘贴到该浏览器上,我将得到一个包含我的用户名的页面,但如果我从代码执行网络请求,我会得到一个空页面。
我的问题是如何作为浏览器打开 url 或者如何在特定浏览器上获取 cookie 的值
我已经尝试过了
string s= GetHtmlPage("http://www.somedomain.com/account/show_cookies.php","Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)");
static string GetHtmlPage(string strURL,string browser)
{
String strResult;
System.Net.WebResponse objResponse;
System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(strURL);
((System.Net.HttpWebRequest)objRequest).UserAgent =browser;
objResponse = objRequest.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
sr.Close();
}
return strResult;
}
但这也会返回一个空白页。
你需要使用Http客户端 http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx and Cookie容器 http://msdn.microsoft.com/ru-ru/library/system.net.httpwebrequest.cookiecontainer.aspx
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync("http://google.com").Result;
Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);
Console.ReadLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)