如何在.NET HTTPWEBREQUEST中自动检索/使用IE代理设置
-
18-09-2019 - |
题
是否可以检测/重复使用这些设置?
如何 ?
我得到的例外是,这是连接到的例外 http://www.google.com
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: A connection attempt failed because the
connected party did not properly respond after a period of time, or established
connection failed because connected host has failed to respond 66.102.1.99:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at mvcTest.MvcApplication.Application_Start() in
C:\\home\\test\\Application1\\Application1\\Program.cs:line 33"
解决方案
默认情况下,HTTPWebRequest实际上将使用IE代理设置。
如果你 别 想要使用它们,您必须专门覆盖为null(无代理)或您选择的代理设置的.proxy专有。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://news.bbc.co.uk");
//request.Proxy = null; // uncomment this to bypass the default (IE) proxy settings
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Done - press return");
Console.ReadLine();
其他提示
我得到的情况非常相似,默认情况下,httpwebrequest并未访问正确的代理详细信息,并且设置underefaultcredentials也无法使用。然而,强迫代码中的设置有所帮助:
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;
}
而且由于这使用默认凭据,因此不应向用户询问其详细信息。
请注意,这是我在此处发布的答案的重复,出于一个非常相似的问题: c#中的代理基本身份验证:http 407错误
对于让ISA服务器播放的问题的人,您可能会尝试以以下方式设置代理:
IWebProxy webProxy = WebRequest.DefaultWebProxy;
webProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
myRequest.Proxy = webProxy;
默认情况下,如果未明确设置WebRequest.proxy(默认情况下,将其设置为 WebRequest.DefaultWebProxy
).
不隶属于 StackOverflow