问题描述
我使用WebBrowser控件登录的任何网站。然后我想下载使用WebRequest类(或Web客户端)部分子页面的HTML。此链接必须需要验证。
I'm using webbrowser control to login any site. And then i want to download some sub page html using WebRequest (or WebClient). This links must requires authentication.
如何传输的网页浏览器认证信息的WebRequest或Web客户端?
How to transfer Webbrowser authentication information to Webrequest or Webclient?
推荐答案
如果问题仅仅是如何的网页浏览器的认证信息传递给WebRequest的或者Web客户端?这code是不够的:
If the question is only "How to transfer Webbrowser authentication information to Webrequest or Webclient?" this code is enough:
您可以调用GetUriCookieContainer方法返回可用于使用WebRequest对象后续调用一个的CookieContainer。
You can call the GetUriCookieContainer method that returns you a CookieContainer that can be used for subsequent call with WebRequest object.
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetGetCookieEx(
string url,
string cookieName,
StringBuilder cookieData,
ref int size,
Int32 dwFlags,
IntPtr lpReserved);
private const Int32 InternetCookieHttponly = 0x2000;
/// <summary>
/// Gets the URI cookie container.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public static CookieContainer GetUriCookieContainer(Uri uri)
{
CookieContainer cookies = null;
// Determine the size of the cookie
int datasize = 8192 * 16;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(
uri.ToString(),
null, cookieData,
ref datasize,
InternetCookieHttponly,
IntPtr.Zero))
return null;
}
if (cookieData.Length > 0)
{
cookies = new CookieContainer();
cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
}
return cookies;
}
这篇关于是否有可能从转移的网页浏览器身份验证的WebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!