2011-11-22 120 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