2010-10-01 52 views
6

說如果我把www.abc.com放入瀏覽器,瀏覽器會自動重定向到www.xyz.com。我需要從服務器端獲取重定向url。也就是說,如果www.abc.com返回重定向網址www.xyz.com,如何從原始URL(www.abc.com)請求重定向網址(www.xyz.com)?如何獲得重定向響應

回答

18

下面是從網絡爬蟲,說明如何處理重定向一個片段:

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

完美。日Thnx。 – Rahatur 2010-10-01 16:43:02

+1

出於某種原因,我的編輯未被接受......以這種方式調用'Close()'是一種不好的做法,您應該使用'using'來代替。 – 2014-02-19 13:36:31

+1

這不適合我。儘管我能夠連接到資源,但我得到了一個空值 – 2014-08-28 19:57:19

相關問題