我有一个包含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()
的位置。凭据是正确的,因为它在我手动执行时有效。
我是否可以以编程方式验证代理凭据?
答案 0 :(得分:3)
// 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;
答案 1 :(得分:2)
这些都不会起作用。由于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中使用它
答案 2 :(得分:0)
这里有一个解决方案:
http://www.journeyintocode.com/2013/08/c-webbrowser-control-proxy.html
它使用winnet.dll
以及WebBrowser
类上的几个界面,包括IAuthenticate
。
我还没能尝试,但看起来很有希望。