我正在尝试使用 HttpwebRequest 和 Httpwebresponse 通过 POST 登录网站,然后在通过身份验证后将其重定向到新站点中的默认页面。我可以执行 responsereader.ReadttoEnd(),但我不确定如何获得自动重定向。
Dim ccContainer As New CookieContainer()
Dim encoding As New ASCIIEncoding()
Dim strId As String = "username"
Dim strName As String = "password"
Dim postData As String = "UAPMURL=&UAPMURLxx=xx&login=" & strId
postData += ("&password1=" & strName)
Dim data As Byte() = encoding.GetBytes(postData)
' Prepare web request...
Dim myRequest As HttpWebRequest = DirectCast(WebRequest.Create("http://www.LOGINURLHERE.COM/LOGIN.PHP?"), HttpWebRequest)
Dim cc As New CookieContainer
' <<--- This is the key word of the day
myRequest.Method = "POST"
myRequest.AllowAutoRedirect = False
myRequest.ContentType = "application/x-www-form-urlencoded"
myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
myRequest.KeepAlive = True
myRequest.CookieContainer = New CookieContainer()
myRequest.ContentLength = data.Length
Dim newStream As Stream = myRequest.GetRequestStream()
' Send the data.
newStream.Write(data, 0, data.Length)
newStream.Close()
Dim _response As HttpWebResponse = DirectCast(myRequest.GetResponse(), HttpWebResponse)
If myRequest.HaveResponse Then
For Each retCookie As Cookie In _response.Cookies
cc.Add(retCookie)
Next
End If
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://www.DESTINATIONURL.COM/Main.php"), HttpWebRequest)
request.CookieContainer = cc
request.AllowAutoRedirect = False
Dim _res As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
如果我这样做...
注释掉这一行
'Dim _res As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
使用这些...它读取并使用来自目标 URL 的数据填充我的当前页面。我是否缺少让它自动重定向的东西?谢谢
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://www.destinationurl.com"), HttpWebRequest)
request.CookieContainer = cc
request.AllowAutoRedirect = False
Dim responseReader As New StreamReader(request.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
Response.Write(responseData)
最佳答案
你不重定向;服务器重定向。
- 如果服务器向您发送重定向响应(代码=3xx),您请求它重定向到的 URL。
- 如果透明处理重定向,
_response.ResponseURI
将包含它重定向到的地址。如果没有,您必须阅读重定向 header 并自行决定是否请求新页面。 - 如果服务器根本不重定向,您只需在获得身份验证 cookie 后请求您想要的任何 URL。
关于c# - HttpWebRequest 登录数据 然后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7731422/