使用自动代理登录的WebBrowser控件
本文关键字:WebBrowser 控件 登录 代理 | 更新日期: 2023-09-27 17:57:57
我有一个包含WebBrowser
控件的windows窗体应用程序。这个想法是让WebBrowser
在没有用户交互的情况下浏览网站。WebBrowser
通过代理访问互联网。
我可以看到代理上的请求,但由于代理身份验证失败,请求被拒绝。
我添加了Proxy-Authorization: Basic
标头。这适用于普通的http页面,但似乎不起作用https:
var credentialStringValue = "proxyUser:proxyPassword";
byte[] credentialByteArray = ASCIIEncoding.ASCII.GetBytes(credentialStringValue);
var credentialBase64String = Convert.ToBase64String(credentialByteArray);
string Headers = string.Format("Proxy-Authorization: Basic {0}{1}", credentialBase64String, Environment.NewLine);
ws.Navigate(url,TargetFrameName,PostData,Headers);
其中ws
等于new WebBrowser()
。凭据是正确的,因为当我手动操作时它可以工作。
你知道我如何用程序验证代理凭据吗?
// do what you want with proxy class
WebProxy webProxy = new WebProxy(host, port)
{
Credentials = ...
}
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://example.com");
webRequest.Proxy = webProxy;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentStream = receiveStream;
这些都不起作用。由于windows的安全功能,它总是会弹出用户名和密码对话框。您首先必须将凭据存储在windows凭据中。您需要做的第一件事是通过NuGet包管理器下载CredentialManagement包。您首先必须将代理信息与用户名和密码一起存储在注册表中。这是注册表的代码
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static void setProxyRegistry(string proxyhost, bool proxyEnabled, string username, string password)
{
const string userRoot = "HKEY_CURRENT_USER";
const string subkey = "Software''Microsoft''Windows''CurrentVersion''Internet Settings";
const string keyName = userRoot + "''" + subkey;
Registry.SetValue(keyName, "ProxyServer", proxyhost, RegistryValueKind.String);
Registry.SetValue(keyName, "ProxyEnable", proxyEnabled ? "1" : "0", RegistryValueKind.DWord);
Registry.SetValue(keyName, "ProxyPass", password, RegistryValueKind.String);
Registry.SetValue(keyName, "ProxyUser", username, RegistryValueKind.String);
//<-loopback>;<local>
Registry.SetValue(keyName, "ProxyOverride", "*.local", RegistryValueKind.String);
// These lines implement the Interface in the beginning of program
// They cause the OS to refresh the settings, causing IP to realy update
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
然后你需要设置凭据
Credential credentials= new Credential
{
Username = "Usernmae",
Password = "Password",
Target = "Target (usualy proxy domain)",
Type = CredentialType.Generic,
PersistanceType = PersistanceType.Enterprise
};
credentials.Save();
我将其与.NET 4.5.2 一起使用
这里发布了一个解决方案:
http://www.journeyintocode.com/2013/08/c-webbrowser-control-proxy.html
它使用winnet.dll
以及WebBrowser
类上的几个接口,包括IAuthenticate
。
我没能尝试,但看起来很有希望。