2010-01-10 131 views
10

我試圖獲取某些網頁的HTML代碼, 我有一個用戶名和密碼是正確的,但我仍然無法使它工作, 這是我的代碼:遠程服務器返回錯誤:(401)未授權

private void buttondownloadfile_Click(object sender, EventArgs e) 
{ 
    NetworkCredentials nc = new NetworkCredentials("?", "?", "http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR"); 
    WebClient client = new WebClient(); 

    client.Credentials = nc; 
    String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR"); 

    MessageBox.Show(htmlCode); 
} 

在MessageBox是隻是爲了測試它, 問題是,每次我去這個線時間:

String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR"); 

我得到一個異常:

The remote server returned an error: (401) Unauthorized.

我該如何解決這個問題?

回答

3

嘗試不說域部分創建NetworkCredential

NetworkCredential nc = new NetworkCredential("?", "?"); 
+0

感謝它爲我工作 – 2017-07-06 10:36:02

6

我曾嘗試下面的代碼,它工作正常。

private void Form1_Load(object sender, EventArgs e)   
    { 
     try 
     { 
      // Create Request 
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://192.168.0.181/axis-cgi/com/ptz.cgi?move=up"); 

      // Create Client 
      WebClient client = new WebClient(); 

      // Assign Credentials 
      client.Credentials = new NetworkCredential("root", "a"); 

      // Grab Data 
      string htmlCode = client.DownloadString(@"http://192.160.0.1/axis-cgi/com/ptz.cgi?move=up"); 

      // Display Data 
      MessageBox.Show(htmlCode); 
     } 
     catch (WebException ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 
+0

,真正起作用...完美! :)謝謝一噸Rahat :) – Bravo 2012-12-21 19:13:12

+12

HttpWebRequest有什麼意義? – Nacht 2013-02-05 08:27:19

13

在我的情況下,client.UseDefaultCredentials = true;做到了。

相關問題