HttpWebRequest登录数据然后重定向
本文关键字:重定向 然后 数据 登录 HttpWebRequest | 更新日期: 2023-09-27 18:11:03
我试图使用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)
不能重定向;服务器重定向。
- 如果服务器发送给你一个重定向响应(code=3xx),你请求它重定向到的URL。
- 如果重定向是透明处理的,
_response.ResponseURI
将包含它重定向到的地址。如果没有,你必须阅读重定向头,并决定是否请求新的页面。 - 如果服务器根本不重定向,你只需要请求任何你想要的URL,一旦你有你的身份验证cookie。