簡體   English   中英

如何在Redrected頁面上進行GET / POST時,讓HttpWebRequest.AllowAutoRedirect設置cookie?

[英]How to get HttpWebRequest.AllowAutoRedirect to set the cookies when doing a GET/POST on the redrected page?

有沒有辦法讓HttpWebRequest對象在通過AllowAutoRedirect功能自動重定向到另一個頁面時考慮到set-cookie標頭? 我需要它來維護重定向的cookie信息; 如果框架可以為我做這個,我寧願不必自己實現重定向。 這必須是一個常見的請求,因為我見過的大多數登錄頁面通常會這樣做。

我知道要使單獨的請求(即不同的HttpRequest對象)使用cookie,您需要在對CookieContainer的同一實例的兩個請求上設置HttpRequest.CookieContainer屬性。 對於這種情況,您可能也需要這樣做。

如果您不想使用CookieContainer,以下代碼將訪問頁面,在參數中提供cookie。 然后,它將下載該頁面設置的所有cookie並將其作為字符串列表返回。

請注意,AllowAutoRedirect設置為false。 如果要跟隨重定向,請將該對象從HttpWebResponse標頭中拉出,然后手動構建另一個Web請求。

Public Shared Function GetCookiesSetByPage(ByVal strUrl As String, ByVal cookieToProvide As String) As IEnumerable(Of String)

    Dim req As System.Net.HttpWebRequest
    Dim res As System.Net.HttpWebResponse
    Dim sr As System.IO.StreamReader

    '--notice that the instance is created using webrequest 
    '--this is what microsoft recomends 
    req = System.Net.WebRequest.Create(strUrl)

    'set the standard header information 
    req.Accept = "*/*"
    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)"
    req.ContentType = "application/x-www-form-urlencoded"
    req.AllowAutoRedirect = False
    req.Headers.Add(HttpRequestHeader.Cookie, cookieToProvide)
    res = req.GetResponse()

    'read in the page 
    sr = New System.IO.StreamReader(res.GetResponseStream())
    Dim strResponse As String = sr.ReadToEnd

    'Get the cooking from teh response
    Dim strCookie As String = res.Headers(System.Net.HttpResponseHeader.SetCookie)
    Dim strRedirectLocation As String = res.Headers(System.Net.HttpResponseHeader.Location)
    Dim result As New List(Of String)
    If Not strCookie = Nothing Then
        result.Add(strCookie)
    End If
    result.Add(strRedirectLocation)
    Return result
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM