我在.NET 3.5中使用此代码并收到错误“远程服务器返回错误:(407)需要代理验证.”
using (WebClient client = new WebClient()) { WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials; try { string webPageStr = client.DownloadString(URL); Console.WriteLine("OK"); } catch (Exception ex) { Console.WriteLine("FAIL"); Console.WriteLine(ex.Message); } }
但是,此代码可以在.NET 4.0中顺利运行,因为此行足以传递代理身份验证,而不适用于.NET 3.5.
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
1)用.替换CredentialCache.DefaultCredentials行
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(user,password,domain);
2)创建新的代理对象
IWebProxy proxy = new WebProxy(proxyUrl,port); proxy.Credentials = new NetworkCredential(user,pass,domain); client.Proxy = proxy; client.Credentials = new NetworkCredential(user,domain);
3)添加此行
client.UseDefaultCredentials = true;
4)使用HttpWebRequest而不是WebClient并重复上面的每个过程.这是示例代码.
HttpWebRequest webRequest = WebRequest.Create(URL) as HttpWebRequest; webRequest.Proxy = WebRequest.DefaultWebProxy; webRequest.Credentials = new NetworkCredential(user,domain); webRequest.Proxy.Credentials = new NetworkCredential(user,domain); try { webRequest.GetResponse(); Console.WriteLine("OK"); } catch (Exception ex) { Console.WriteLine("FAIL"); Console.WriteLine(ex.Message); }
因为我必须使用.NET 3.5,所以我觉得自己走到了尽头.我不知道这两个.NET版本之间必须有区别.非常感谢你提前.
解决方法
只需将此添加到配置
<system.net> <defaultProxy useDefaultCredentials="true" > </defaultProxy> </system.net>