【发布时间】:2009-12-01 10:04:34
【问题描述】:
对于我正在进行的项目,我们有一个桌面程序,可以联系在线服务器以获取商店。因为它在学校中使用,所以正确设置代理很棘手。我们所追求的是允许用户指定要使用的代理详细信息(如果他们愿意),否则它使用来自 IE 的代理详细信息。我们还尝试绕过输入的错误详细信息,因此代码会尝试用户指定的代理,如果失败则使用默认代理,如果失败则使用凭据,如果失败则为 null。
我遇到的问题是,在需要连续更改代理设置的地方(例如,如果由于代理错误而导致注册失败,他们会更改一件小事,然后重试,需要几秒钟。)我最终调用 HttpRequests .GetResponse() 超时,导致程序冻结了很长一段时间。有时,如果我在更改之间留出一两分钟,它不会冻结,但不是每次都冻结(现在在 10 分钟后再次尝试,它又超时了)。
我无法在代码中发现任何可能导致此问题的内容 - 尽管它看起来有点混乱。我不认为这可能是服务器拒绝请求,除非它是通用的服务器行为,因为我已经尝试过对我们的服务器和其他服务器(如 google.co.uk)的请求。
我发布代码是希望有人能够发现其中的问题,或者知道一种更简单的方法来做我们正在尝试做的事情。
我们运行的测试没有任何代理,因此通常会跳过第一部分。第一次运行 ApplyProxy 时,它工作正常并在第一个 try 块中完成所有内容,第二次,它可以在第一个 try 块中的 GetResponse 超时,然后执行其余代码,或者它可以在那里工作并且实际注册请求超时。
代码:
无效应用代理() {
Boolean ProxySuccess = true;
String WebRequestURI = @"http://www.google.co.uk";
if (UseProxy)
{
try
{
String ProxyUrl = (ProxyUri.ToLower().Contains("http://")) ?
ProxyUri :
"http://" + ProxyUri;
WebRequest.DefaultWebProxy = new WebProxy(ProxyUrl);
if (!string.IsNullOrEmpty(ProxyUsername) && !string.IsNullOrEmpty(ProxyPassword))
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(ProxyUsername, ProxyPassword);
HttpWebRequest request = HttpWebRequest.Create(WebRequestURI) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch
{
ProxySuccess = false;
}
}
if(!ProxySuccess || !UseProxy)
{
try
{
WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
HttpWebRequest request = HttpWebRequest.Create(WebRequestURI) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch (Exception e)
{ //try with credentials
//make a new proxy from defaults
WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
String newProxyURI = WebRequest.DefaultWebProxy.GetProxy(new Uri(WebRequestURI)).ToString();
if (newProxyURI == String.Empty)
{ //check we actually get a result
WebRequest.DefaultWebProxy = null;
return;
}
//continue
WebProxy NewProxy = new WebProxy(newProxyURI);
NewProxy.UseDefaultCredentials = true;
NewProxy.Credentials = CredentialCache.DefaultCredentials;
WebRequest.DefaultWebProxy = NewProxy;
try
{
HttpWebRequest request = HttpWebRequest.Create(WebRequestURI) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch
{
WebRequest.DefaultWebProxy = null;
}
}
}
}
【问题讨论】: