2010-10-01 16 views
6

Dire se inserisco www.abc.com nel browser, il browser viene automaticamente reindirizzato su www.xyz.com. Ho bisogno di ottenere l'URL di reindirizzamento dal lato server. Cioè, se www.abc.com restituisce un URL di reindirizzamento www.xyz.com, come posso richiedere questo URL di reindirizzamento (www.xyz.com) dall'URL originale (www.abc.com)?Come ottenere una risposta di reindirizzamento

risposta

18

Ecco un frammento da un web crawler che mostra come gestire redirect:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 
    webRequest.AllowAutoRedirect = false; // IMPORTANT 
    webRequest.UserAgent = ...; 
    webRequest.Timeout = 10000;   // timeout 10s 

    // Get the response ... 
    using (webResponse = (HttpWebResponse)webRequest.GetResponse()) 
    { 
    // Now look to see if it's a redirect 
    if ((int)webResponse.StatusCode >= 300 && (int)webResponse.StatusCode <= 399) 
    { 
     string uriString = webResponse.Headers["Location"]; 
     Console.WriteLine("Redirect to " + uriString ?? "NULL"); 
     ... 
    } 
    } 
+0

ha funzionato perfettamente. thnx. – Rahatur

+1

Per qualche motivo la mia modifica non è stata accettata ... Chiamare 'Close()' in questo modo è una cattiva pratica, dovresti usare 'using'. –

+1

questo non funziona per me. Sto ottenendo un valore nullo anche se sono in grado di connettermi alla risorsa –

Problemi correlati