代码之家  ›  专栏  ›  技术社区  ›  Mark

如何获取httpwebrequest.allowautoredirect以在重绘页上执行get/post时设置cookie?

  •  11
  • Mark  · 技术社区  · 17 年前

    有没有办法 HttpWebRequest 对象,以便在通过 AllowAutoRedirect 特色?我需要它来维护跨重定向的cookie信息;如果框架能够为我做这件事,我宁愿不需要自己实现重定向。这一定是一个常见的请求,因为我看到的大多数登录页面通常都会这样做。

    2 回复  |  直到 17 年前
        1
  •  5
  •   Jonathan Rupp    17 年前

    我知道要使不同的请求(即不同的httpRequest对象)与cookie一起工作,需要设置 HttpRequest.CookieContainer 对同一实例的两个请求的属性 CookieContainer . 你可能也需要这个。

        2
  •  0
  •   Sean Turner    17 年前

    如果不想使用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
    
    推荐文章