2013-02-17 6 views
6

Sto cercando di scaricare una pagina web utilizzando WebClient e ottenere l'errore interno 500WebClient Il server remoto ha restituito un errore: (500) Internal Server Error

public class AsyncWebClient 
    { 
     public string GetContent(string url) 
     { 
      return GetWebContent(url).Result.ToString(); 
     } 
     private Task<string> GetWebContent(string url) 
     { 
      var wc = new WebClient(); 
      TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(); 

      wc.DownloadStringCompleted += (obj, args) => 
      { 
       if (args.Cancelled == true) 
       { 
        tcs.TrySetCanceled(); 
        return; 
       } 

       if (!String.IsNullOrEmpty(args.Result)) 
        tcs.TrySetResult(args.Result); 
      }; 

      wc.DownloadStringAsync(new Uri(url)); 
      return tcs.Task; 
     } 
    } 

e chiamare:

var wc =new AsyncWebClient(); 
var html = wc.GetContent("http://truyen.vnsharing.net/"); >> always get the above error 

se uso un altro sito, allora funziona bene. non so cosa c'è di speciale in questo sito.

Si prega di aiutare !!

risposta

13

Probabilmente il server si aspetta un agente utente corretto.

Aggiornare il codice di seguito:

var wc = new WebClient(); 
wc.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(); 
+0

grazie per tutti la risposta. lo apprezzo davvero. –

+1

Se possibile, non impersonare un browser. – svick

+0

svick quale è la ragione per non impersonare un browser nel codice? – rolls