1

我需要使用 HTTPWebRequest 登录到外部网站并将我重定向到默认页面。我下面的代码在一个按钮后面 - 当单击它时,它当前会尝试进行一些处理但保持在同一页面上。我需要它来将我重定向到外部网站的默认页面,而不会看到登录页面。对我做错了什么有帮助吗?

    Dim loginURL As String = "https://www.example.com/login.aspx"

    Dim cookies As CookieContainer = New CookieContainer
    Dim myRequest As HttpWebRequest = CType(WebRequest.Create(loginURL), HttpWebRequest)
    myRequest.CookieContainer = cookies
    myRequest.AllowAutoRedirect = True
    myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1"

    Dim myResponse As HttpWebResponse = CType(myRequest.GetResponse(), HttpWebResponse)

    Dim responseReader As StreamReader
    responseReader = New StreamReader(myResponse.GetResponseStream())
    Dim responseData As String = responseReader.ReadToEnd()
    responseReader.Close()

    'call a function to extract the viewstate needed to login
    Dim ViewState As String = ExtractViewState(responseData)

    Dim postData As String = String.Format("__VIEWSTATE={0}&txtUsername={1}&txtPassword={2}&btnLogin.x=27&btnLogin.y=9", ViewState, "username", "password")
    Dim encoding As UTF8Encoding = New UTF8Encoding()
    Dim data As Byte() = encoding.GetBytes(postData)

    'POST to login page
    Dim postRequest As HttpWebRequest = CType(WebRequest.Create(loginURL), HttpWebRequest)
    postRequest.Method = "POST"
    postRequest.AllowAutoRedirect = True
    postRequest.ContentLength = data.Length
    postRequest.CookieContainer = cookies
    postRequest.ContentType = "application/x-www-form-urlencoded"
    postRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1"

    Dim newStream = postRequest.GetRequestStream()
    newStream.Write(data, 0, data.Length)
    newStream.Close()

    Dim postResponse As HttpWebResponse = CType(postRequest.GetResponse(), HttpWebResponse)

   'using GET request on default page
    Dim getRequest As HttpWebRequest = CType(WebRequest.Create("https://www.example.com/default.aspx"), HttpWebRequest)
    getRequest.CookieContainer = cookies
    getRequest.AllowAutoRedirect = True

    Dim getResponse As HttpWebResponse = CType(getRequest.GetResponse(), HttpWebResponse)
    'returns statuscode = 200

仅供参考 - 当我在最后添加此代码时,我得到了我试图重定向到的默认页面的 HTML

Dim responseReader1 As StreamReader
responseReader1 = New StreamReader(getRequest.GetResponse().GetResponseStream())

responseData = responseReader1.ReadToEnd()
responseReader1.Close()
Response.Write(responseData)

有关使重定向工作缺少什么的任何帮助?

干杯

4

1 回答 1

0

HttpWebRequest 仅当服务器在响应中发送带有 Location 字段的 HTTP 3xx 重定向状态时才会自动重定向您。否则,您应该使用 Response.Redirect 手动导航到页面。还要记住,自动重定向会忽略服务器发送的任何 COOKIES。如果服务器实际上正在发送重定向状态,这可能是您的问题。

于 2012-09-29T20:52:07.067 回答