如何在.net HttpWebRequest中自动检测/使用IE代理设置

时间:2009-07-20 19:14:33

标签: c# proxy httpwebrequest detect

是否可以检测/重复使用这些设置?

怎么样?

我得到的例外是 这是连接到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"

4 个答案:

答案 0 :(得分:24)

默认情况下,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 :(得分: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

答案 2 :(得分:2)

对于在使用ISA服务器时遇到问题的人,您可能会尝试以下列方式设置代理:

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

答案 3 :(得分:1)

默认情况下会发生这种情况,如果未明确设置WebRequest.Proxy(默认设置为WebRequest.DefaultWebProxy)。