我有一个使用Webclient登录到网站(POST表单)的vb.net控制台应用程序:
Dim responsebytes = myWebClient.UploadValues("https:!!xxx.com/mysession/create", "POST", myNameValueCollection)
上周五,这突然停止工作,大约2 - 3年没有问题。使用Fiddler我收到了HTTP 504错误但没有Fiddler我得到了错误消息:
基础连接已关闭:连接意外关闭。
我认为服务器端的某些内容已发生变化,但我对此没有任何影响。这是一个商业网站,我想在我的帐户上自动登录以获取一些数据。
由于Fiddler无法帮助我,我决定构建一个基本的HttpWebRequest示例,以排除它是由WebClient引起的。
示例确实:
Public Class Form1
Const ConnectURL = "https:!!member.company.com/homepage/index"
Const LoginURL = "https:!!member.company.com/account/logn"
Private Function RegularPage(ByVal URL As String, ByVal CookieJar As CookieContainer) As String
Dim reader As StreamReader
Dim Request As HttpWebRequest = HttpWebRequest.Create(URL)
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
Request.AllowAutoRedirect = False
Request.CookieContainer = CookieJar
Dim Response As HttpWebResponse = Request.GetResponse()
reader = New StreamReader(Response.GetResponseStream())
Return reader.ReadToEnd()
reader.Close()
Response.Close()
End Function
Private Function LogonPage(ByVal URL As String, ByRef CookieJar As CookieContainer, ByVal PostData As String) As String
Dim reader As StreamReader
Dim Request As HttpWebRequest = HttpWebRequest.Create(URL)
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
Request.CookieContainer = CookieJar
Request.AllowAutoRedirect = False
Request.ContentType = "application/x-www-form-urlencoded"
Request.Method = "POST"
Request.ContentLength = PostData.Length
Dim requestStream As Stream = Request.GetRequestStream()
Dim postBytes As Byte() = Encoding.ASCII.GetBytes(PostData)
requestStream.Write(postBytes, 0, postBytes.Length)
requestStream.Close()
Dim Response As HttpWebResponse = Request.GetResponse()
For Each tempCookie In Response.Cookies
CookieJar.Add(tempCookie)
Next
reader = New StreamReader(Response.GetResponseStream())
Return reader.ReadToEnd()
reader.Close()
Response.Close()
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CookieJar As New CookieContainer
Dim PostData As String
Try
Dim homePage As String = (RegularPage(ConnectURL, CookieJar))
Dim securityToken = homePage.Substring(homePage.IndexOf("securityToken") + 22, 36) 'momenteel 36 characters lang
PostData = "securityToken=" + securityToken + "&accountId=123456789&password=mypassword"
MsgBox(PostData)
Dim accountPage As String = (LogonPage(LoginURL, CookieJar, PostData))
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
结束班
此行导致连接关闭:
Dim requestStream As Stream = Request.GetRequestStream()
该公司是否可能不喜欢自动登录并以某种方式注意到应用程序用于登录?我该怎么调试呢?提琴手似乎不起作用。我唯一的选择是WireShark,因为这对我来说似乎很难。
在我发布帖子之前连接已经关闭也很奇怪? 是否有其他语言我可以“轻松”编程,以排除它的VB.net / .NET问题?
答案 0 :(得分:0)
您是否曾尝试使用浏览器的网络工具捕获请求?
身份验证过程可能已更改。甚至可以是一些名称或发布数据更改。
答案 1 :(得分:0)
我解决了这个问题:
仔细检查使用浏览器时要发送的所有标题
确保所有那些由VB.NET应用程序发送的标题。
不确定哪一个做了这个技巧,但总是确保你复制浏览器发送的所有标题!