2009-07-20 28 views
17

是否可以检测/重用这些设置?如何在.net中自动检测/使用IE代理设置HttpWebRequest

怎么样?

例外我得到是 这是例外,而连接到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" 
+0

如果你得到一个异常,请张贴整个事情:ex.ToString()。 – 2009-07-20 19:36:20

+0

异常高于 – Kumar 2009-07-21 18:57:41

+0

这更可能是防火墙问题。你只是没有获得连接。 – 2009-07-21 19:01:43

回答

23

默认情况下,HttpWebRequest实际上会使用IE代理设置。

如果你不要想要使用它们,你必须明确地重写.Proxy属性为null(无代理)或你选择的代理设置。

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(); 
1

这发生在默认情况下,如果没有明确设置WebRequest.Proxy(默认情况下它被设置为WebRequest.DefaultWebProxy)。

2

另外,具有得到这个播放使用ISA服务器不错,你可以尝试设置代理按以下方式问题的人:

IWebProxy webProxy = WebRequest.DefaultWebProxy; 
webProxy.Credentials = CredentialCache.DefaultNetworkCredentials; 
myRequest.Proxy = webProxy; 
7

我得到一个非常类似的情况,其中的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; 
} 

因为这使用默认凭据,它不应该要求用户的细节。

注意,这是我的答案贴在这里的一个非常类似的问题的重复:Proxy Basic Authentication in C#: HTTP 407 error