2010-04-08 124 views
27

我有一個返回HTTP 302重定向的URL,我想獲取它重定向到的URL。從WebClient獲取HTTP 302重定向的位置?

問題是,System.Net.WebClient似乎實際上跟着它,這是不好的。 HttpWebRequest似乎也這樣做。

有沒有辦法制作一個簡單的HTTP請求並取回沒有WebClient的目標位置?

我很想做原始套接字通信,因爲HTTP足夠簡單,但該網站使用HTTPS,我不想做握手。

最後,我不在乎我使用哪一類,我只是不希望它遵循HTTP 302個重定向:)

回答

17

HttpWebRequest您可以設置AllowAutoRedirectfalse處理重定向自己。

14

HttpWebRequest有一個屬性AllowAutoRedirect,您可以將其設置爲false(it is always true for WebClient),然後獲取Location HTTP標頭。

+0

好注意,它隱藏在該鏈接指向的部分正上方的頁面上。 https://msdn.microsoft.com/zh-cn/library/system.net.webclient.aspx?f=255&MSPPError=-2147217396#Examples – dragon788 2016-11-04 18:53:05

20

這是很容易做到的

讓我們假設你已經創建了一個名爲HttpWebRequest的myRequest

// don't allow redirects, they are allowed by default so we're going to override 
myRequest.AllowAutoRedirect = false; 

// send the request 
HttpWebResponse response = myRequest.GetResponse(); 

// check the header for a Location value 
if(response.Headers["Location"] == null) 
{ 
    // null means no redirect 
} 
else 
{ 
    // anything non null means we got a redirect 
} 

任何藉口編譯錯誤,我沒有VS就在我的面前,但是我過去用它來檢查重定向。

+0

添加允許重定向爲false,因爲這是原始OP的一部分。 – Justin 2012-03-02 21:04:41

+1

錯字:'AllowAutoRedirect'不是'AutoAllowRedirect' – 2013-11-20 13:11:36

+0

@JohnDyer謝謝約翰我更新了這個例子! – Justin 2015-09-01 16:40:47

0

此外,對於只需要新位置的人,HttpResponseMessage擁有RequestMessage屬性。有時它可能很有用,因爲WebClient不支持在設置後更改AllowAutoRedirect屬性。