我正在使用一个需要身份验证的代理,即在浏览器中,如果我试图打开一个页面,它将立即要求提供凭据。我在我的程序中提供了相同的凭据,但它失败了,并显示HTTP407错误。
下面是我的代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
CredentialCache cc = new CredentialCache();
NetworkCredential nc = new NetworkCredential();
nc.UserName = "userName";
nc.Password = "password";
nc.Domain = "mydomain";
cc.Add("http://20.154.23.100", 8888, "Basic", nc);
proxy.Credentials = cc;
//proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Proxy = proxy;
request.Proxy.Credentials = cc;
request.Credentials = cc;
request.PreAuthenticate = true;我已经尝试了所有可能的方法,但我似乎错过了一些东西。是不是像这样,我必须提出两个请求?首先没有凭据,一旦我从服务器得到关于需要凭据的反馈,是否可以使用凭据发出相同的请求?
发布于 2012-03-07 22:58:23
以下是使用代理和证书的正确方法。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;感谢大家的帮助……:)
发布于 2012-08-03 07:11:03
这种方法可以避免硬编码或配置代理凭证的需要,这可能是所希望的。
将其放入您的应用程序配置文件中-可能是app.config。Visual Studio将在构建时将其重命名为yourappname.exe.config,并且它将位于您的可执行文件旁边。如果您没有应用程序配置文件,只需使用Visual Studio中的add New Item添加一个。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>发布于 2013-08-02 17:30:57
我遇到了一个非常类似的情况,在默认情况下,HttpWebRequest没有获取正确的代理详细信息,并且设置UseDefaultCredentials也不起作用。然而,强制代码中的设置起到了很好的效果:
IWebProxy proxy = myWebRequest.Proxy;
if (proxy != null) {
string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString();
myWebRequest.UseDefaultCredentials = true;
myWebRequest.Proxy = new WebProxy(proxyuri, false);
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}因为这使用默认凭证,所以不应该向用户询问它们的详细信息。
https://stackoverflow.com/questions/9603093
复制相似问题