2011-11-22 111 views
3
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.example.com"); 
NetworkCredential nc = new NetworkCredential("myname", "mypass"); 
WebProxy myproxy = new WebProxy("192.168.1.1:8080", false); 
myHttpWebRequest.Proxy = myproxy; 
myHttpWebRequest.Proxy = WebRequest.DefaultWebProxy; 
myHttpWebRequest.Method = "GET"; 

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
MessageBox.Show("Ok"); 

我正在使用此代码与网站(C#.net桌面应用程序)连接。但我有这个错误信息:代理身份验证错误

The remote server returned an error: (407) Proxy Authentication Required.

我该如何解决这个问题?

+0

您是否需要将nc传递给WebProxy构造函数? – spb

回答

2

您目前没有使用代理中的凭据。下面是一个example adapted from MSDN of how to use your NetworkCredential

class Downloader 
{ 
    static void Main(string[] args) 
    { 
     NetworkCredential nc = new NetworkCredential(args[0], args[1]); 
     WebProxy proxy = new WebProxy(args[2], false); 
     proxy.Credentials = nc; 

     WebRequest request = new WebRequest(args[3]); 
     request.Proxy = proxy; 
     using (WebResponse response = request.GetResponse()) 
     { 
      Console.WriteLine(
       @"{0} - {1} bytes", 
       response.ContentType, 
       response.ContentLength); 
     } 
    } 
} 

当我编译和运行这个完整的例子:

C:\cs>csc proxy.cs 
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 
Copyright (C) Microsoft Corporation. All rights reserved. 


C:\cs>proxy user pass http://proxy:80 http://www.google.com 
text/html; charset=ISO-8859-1 - 31398 bytes 

C:\cs> 

当然,我用我的实际用户名/密码和代理对我的工作的帐户。

+0

为什么你使用'CredentialCache' +'NetworkCredential'而不是'NetworkCredential'? – abatishchev

+0

因为我最初是从错误的例子中改编的。更正了,谢谢。 – user7116

+0

谢谢Sixletter – Kevin