我正在使用webbrowser控件登录任何站点。然后,我想使用WebRequest(或WebClient)下载一些子页面html。此链接必须要求身份验证。
如何将Webbrowser身份验证信息传输到Webrequest或Webclient?
最佳答案
如果问题仅是“如何将Webbrowser身份验证信息传输到Webrequest或Webclient?”这段代码就足够了:
您可以调用GetUriCookieContainer方法,该方法将为您返回一个CookieContainer,该CookieContainer可用于随后的WebRequest对象调用。
[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;
}
关于c# - 是否可以将身份验证从Webbrowser转移到WebRequest,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3382498/