Skip to content

Instantly share code, notes, and snippets.

@diaolizhi
Created October 23, 2018 11:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diaolizhi/0592215b72b0f12d3d37c37597a15afa to your computer and use it in GitHub Desktop.
Save diaolizhi/0592215b72b0f12d3d37c37597a15afa to your computer and use it in GitHub Desktop.
C# WebBrowser 获取 HttpOnly 的 cookie
//不知道为什么有些 cookie 获取不到,只能通过这种方式解决
//这一次的用法是,先在 WebBrowser 登录贴吧网页版,然后将 http://tieba.baidu.com/mo/ 传给 GetCookie 方法
//就可以获取到所有 cookie
//需要引入 System.Net 并 using System.Net;
//下面这段代码作为内部类,如何使用在后面
internal static class CookieReader
{
/// <summary>
/// Enables the retrieval of cookies that are marked as "HTTPOnly".
/// Do not use this flag if you expose a scriptable interface,
/// because this has security implications. It is imperative that
/// you use this flag only if you can guarantee that you will never
/// expose the cookie to third-party code by way of an
/// extensibility mechanism you provide.
/// Version: Requires Internet Explorer 8.0 or later.
/// </summary>
private const int INTERNET_COOKIE_HTTPONLY = 0x00002000;
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetGetCookieEx(
string url,
string cookieName,
StringBuilder cookieData,
ref int size,
int flags,
IntPtr pReserved);
/// <summary>
/// Returns cookie contents as a string
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetCookie(string url)
{
int size = 512;
StringBuilder sb = new StringBuilder(size);
if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
{
if (size < 0)
{
return null;
}
sb = new StringBuilder(size);
if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
{
return null;
}
}
return sb.ToString();
}
}
//使用方法
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string cookie = webBrowser1.Document.Cookie;
cookie = CookieReader.GetCookie("http://tieba.baidu.com/mo/");
textBox1.Text = cookie;
}
@zwdgit
Copy link

zwdgit commented Oct 24, 2019

这种方法是不是无法获取到httponly的cookie

@diaolizhi
Copy link
Author

这种方法是不是无法获取到httponly的cookie

不好意思,隔得时间有点久,我不记得细节了,但是我记得是可以获取到的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment