2009-08-29 7 views
1

J'ai toujours utilisé ce code pour donwload la source HTML d'une page Web:HttpWebRequest ne fonctionne pas dans une page web

private string GetHtml(string url) 
{ 
    HttpWebRequest web = (HttpWebRequest)WebRequest.Create(url); 
    web.Method = "GET"; 
    WebResponse resp = web.GetResponse(); 
    Stream istrm = resp.GetResponseStream(); 
    StreamReader sr = new StreamReader(istrm); 
    string html = sr.ReadToEnd(); 
    sr.Close(); 
    resp.Close(); 
    return html; 
} 

Mais il renvoie une chaîne vide lorsque l'URL a cette valeur:

http://actas.rfef.es/actas/RFEF_CmpJornada?cod_primaria=1000144&CodCategoria=100

Répondre

3

Utilisez un cookiejar (et pour le nettoyage, utilisez quelques usings)

 
private string GetHtml(string url) 
{ 
    HttpWebRequest web = (HttpWebRequest)WebRequest.Create(url); 
    web.Method = "GET"; 
    CookieContainer cookieJar = new CookieContainer(); 
    web.CookieContainer = cookieJar; 
    using (WebResponse resp = web.GetResponse()) 
    { 
     using (Stream istrm = resp.GetResponseStream()) 
     { 
      using (StreamReader sr = new StreamReader(istrm)) 
      { 
       string html = sr.ReadToEnd(); 
       sr.Close(); 
       resp.Close(); 
       return html; 
      } 
     } 
    } 
} 

Aussi, ce qui peut également utiliser si les choses commencent à mal tourner à nouveau:

 
    web.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
    web.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"; 
    web.Referer = url; 
+0

Bonne réponse! :-) –

+0

Ça marche! Je vous remercie! – Victor

Questions connexes