我正在将VBScript转换为VB.Net,而我却忙于处理网络请求。
我读过我不需要MSXML2.XMLHTTP对象,但在VB.Net中进行webrequest似乎更复杂。
VBScript源(实际的URL和未给出的帖子字符串):
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
'Submit web requests
oXMLHTTP.Open "GET", sLoginURL, False
oXMLHTTP.Send
oXMLHTTP.Open "POST", sResultsURL, False
oXMLHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXMLHTTP.Send sFormData
oXMLHTTP.Open "GET", sResultsHandlerURL, False
oXMLHTTP.Send
msgbox(oXMLHTTP.ResponseText)
这样可行,并返回带有结果的漂亮JSON字符串。有几点需要注意:
我尝试使用此处的函数:http://www.808.dk/?code-vbnet-httpwebrequest按顺序运行这些请求,但它不起作用。我认为这是因为每次调用函数时它都会创建一个新的HTTPRequest。
我认为它与cookie有关,但不清楚它在vb.net中是如何工作的。
TL; DR。如何将上述脚本转换为vb.net
P.S。为什么在VB.Net中这么复杂?我原以为哈哈会更容易。
答案 0 :(得分:0)
在此实例中尝试使用WebClient类。它处理您引用的示例中的大部分代码,因为它使用WebRequest类。
Dim objWebClient As New WebClient()
objWebClient.DownloadString(sLoginUrl)
objWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
objWebClient.UploadString(sResultsURL, "POST", sFormData)
objWebClient.DownloadString(sResultsHandlerURL)
答案 1 :(得分:0)
我能够在我的帖子中使用Crowcoder的建议。我修改了帖子中链接的功能,如下所示:
Function WRequest(URL As String, method As String, POSTdata As String, ByRef cookieJar As CookieContainer) As String
Dim responseData As String = ""
Try
Dim hwrequest As Net.HttpWebRequest = Net.WebRequest.Create(URL)
hwrequest.CookieContainer = cookieJar
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function
然后将其称为:
Dim cookieJar As New CookieContainer
WRequest(sLoginURL, "GET", "", cookieJar)
WRequest(sResultsURL, "POST", postString, cookieJar)
Debug.Print(WRequest(sResultsHandlerURL, "GET", "", cookieJar))
比VBS更复杂哈哈,但它确实有效!