从Winform C#在浏览器上获取Cookie [英] get cookies on a browser from winform c#

查看:632
本文介绍了从Winform C#在浏览器上获取Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im构建一个应用程序,在用户登录到我的网站后,该应用程序会转到一个链接以获取其用户名,这样我就可以在该应用程序上识别出他.

im building an app that after the the user logs in to my web site the app goes to a link to get his user name so i will recognize him on the app.

现在,如果我作为用户从浏览器登录,然后将类似的内容粘贴到该浏览器上,我将获得一个包含我的用户名的页面,但是如果我从代码中发出一个Web请求,我将获得一个空页面.

Now if i as a user login from a browser and then paste the like on that browser i will get a page with my username but if i do a web request from code i get an empty page.

我的问题是如何在浏览器中打开URL或如何在certin浏览器中获取cookie的值

My question is how to open the url as a browser or how can i get the value of the cookie on a certin browser

我试过了

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;
        }

但这也会返回空白页.

推荐答案

您需要使用 CookieContainer

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();

这篇关于从Winform C#在浏览器上获取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆