I'm setting up a client code written VBScript which probes a text file on a server with HTTP GET requests. The client has actions related to each HTTP response text.
While doing so in a While True loop, the first request returns the correct value. All the preceding requests return the same value the first response did.
The content of the file changes while the HTTP request doesn't seem to leave the client while sniffing packets.
Code:
function checkLog(url)
Dim WshShell, http
Set WshShell = CreateObject("WScript.Shell")
Set http = CreateObject("Microsoft.XmlHttp")
On Error Resume Next
http.open "GET" , url, False
http.send ""
checkLog = http.responseText
End function
Dim lastVal = "2"
Dim logResult = "2"
Do While True
logResult = checkLog("http://10.0.0.3/log.txt")
If logResult <> lastVal Then
If logResult = "0" Then
' Go Func 1
MsgBox "Got 0"
lastVal = logResult
End If
If logResult = "1" Then
' Go Func 2
MsgBox "Got 1"
lastVal = logResult
End If
End If
Sleep 5
LOOP
I expect that a packet will be sent every 5 seconds.
Thanks!
Disable caching of the HTTP response.
Set req = CreateObject("Msxml2.XmlHttp")
On Error Resume Next
req.Open "GET", url, False
req.SetRequestHeader "Cache-Control", "no-cache"
req.Send ""
checkLog = req.ResponseText
Related
I use the following function to check if a RSS url is healthy then consume it:
function testUrl(url)
testUrl=0
Set o = CreateObject("MSXML2.XMLHTTP")
on error resume next
o.open "GET", url, false
o.send
if o.Status = 200 then testUrl = 1
on error goto 0
set o=nothing
end function
However when the target URL does not respond in a short time I will get timeout error. So I want to use the following function in this Q/A to terminate the request after 5 seconds if there was no success response but I dont know where to put the asp_Wait(5) and how to cancel the request after 5 seconds? Should I put asp_Wait right after the o.send or o.send acts synchronous?
Function asp_Wait(nMilliseconds)
Dim oShell
Set oShell= Server.CreateObject("WScript.Shell")
Call oShell.run("ping 1.1.1.1 -n 1 -w " & nMilliseconds,1,TRUE)
End Function
If using the WinHTTPRequest object you can call the WaitForResponse method.
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", url, true 'async request
o.send
If o.waitForResponse(5) Then 'wait 5 sec
...
Else 'wait timeout exceeded
...
End If
I use the following function to check if a URL responds in a few seconds:
function testUrl(url)
Set xmlDOM = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlDOM.Open "GET", url, False
xmlDOM.setTimeouts 1000,1000,1000,1000
testUrl=xmlDOM.Send
end function
if testUrl("http://khabarfoori.com/rss/mm") then
responsw.write "active"
else
response.write "inactive"
end if
Instead of getting "active" or "inactive" I get the following error:
> msxml6.dll error '80072ee2'
> The operation timed out
Footnote: The tested URL above buffers a big amount of text with no server error. Is it a special case and I need more code to handle this kind of response?
May be this can did the trick !
feed = "http://khabarfoori.com/rss/mm"
Set req = CreateObject("Msxml2.ServerXMLHTTP.6.0")
req.Open "GET", feed, False
req.Send
Set xml = CreateObject("Msxml2.DOMDocument")
xml.loadXml(req.responseText)
First_Title = xml.getElementsByTagName("channel/item/title")(0).Text
If Len(First_Title) <> 0 Then
MsgBox "active"
MsgBox First_Title
else
MsgBox"inactive"
End If
I'm trying to send a HTTP get to an internal webserver and this works fine unless due to rerouting reasons, a user has to traverse a proxy in order to get to the webserver, then I just get a WinInet 12029 error of "ERROR_INTERNET_CANNOT_CONNECT The attempt to connect to the server failed." Please can you help me pull in the existing Internet Options proxy config? I don't want to define the proxy credentials statically (nor have I tried).
My code:
Function HTTPGet1
Dim o, URL, stat
URL = myURL
On Error Resume Next
Set o = CreateObject("Microsoft.XMLHTTP")
' If Err.Number <> 0 Then
'msgbox err.Number & err.Description
'msgbox "cake"
'Exit Function
' End if
o.WinHttpGetIEProxyConfigForCurrentUser
o.open "GET", URL, False
o.send
stat = o.Status 'CInt(o.Status)
if stat = "200" then
msgbox "Account created successfully."
elseif stat = "" then
msgbox "Connection attempt failed due to: " & err.description & "."
err.clear
else
msgbox "HTTP error code " & stat & " received."
end if
end function
Thanks for your time!
Use the latest version of ServerXMLHTTP object
Set xHttp= CreateObject("MSXML2.ServerXMLHTTP.6.0")
xHttp.Open "POST", SERVER_URL, data, False
xHttp.setProxy 2, "<Your proxy URL>:<PORT>", ""
xHttp.send
response = xHttp.responseText
msgbox xHttp.status & "|" & xHttp.statustext
msgbox "Response for get call is :" & response
A pcap uncovered that the server was responding with a SSL cert error that this API couldn't respond to. I swapped it out for MSXML2.ServerXMLHTTP.6.0 and then was able to handle the host name mismatch.
Function HTTPGet1
Dim o, address, caseNo, URL, stat
URL = myURL
On Error Resume Next
Set o = CreateObject("MSXML2.ServerXMLHTTP.6.0")
If Err.Number <> 0 Then
msgbox err.Number & err.Description
err.clear
Exit Function
End if
o.setOption 2, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS
o.open "GET", URL, False
o.send
stat = o.Status
The parameter 'SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS' is just one of the options available via the API and this one is not the most secure.
I am having a VBScript which gets invoked from a 3rd party application, the script gets the data from the 3rd party application and opens the URL in an IE browser by passing the data in POST format. The script works fine when I use http as the protocol but the moment I use https, the server side code (request.getParameter("param1")) complains that it is not able to find the parameter in the request object. The script is called by passing the URL and the data. e.g. run.vbs https://xyz.com?param1=1234. Following is the vbscript for your kind perusal. Can you please let me know what I am missing when I am using https as the protocol. Any help is highly appreciated. Many thanks.
If WScript.Arguments.Count = 1 Then
uri = WScript.Arguments.Item(0)
'WScript.Echo "Arguments " & uri
Set WshNetwork = WScript.CreateObject("WScript.Network")
'WScript.Echo "Current User Name: " & WshNetwork.UserName
filename="C:\Documents and Settings\"+WshNetwork.UserName+"\Application Data\XYZ\Profiles\default\Settings.xml"
'WScript.Echo "Current User fileName: " & filename
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.Load(filename)
strQuery = "Agent"
Set colItem = xmlDoc.getElementsByTagname(strQuery)
For Each objItem in colItem
Agentid = objItem.getAttribute("Login")
'MsgBox "AgentId = " + AgentID
Next
'uri = uri+"^&agentid="+Agentid
uri = uri+"&agentid="+Agentid
pos = InStr(uri,"?")
extracteduri = Mid(uri,1,pos-1)
params = Mid(uri, pos+1)
postdata = Str2Bytes(params,"us-ascii")
header = "Content-Type: application/x-www-form-urlencoded"
Set IE = CreateObject("InternetExplorer.Application")
'IE.Navigate "about:blank"
'IE.AddressBar = True
'IE.ToolBar = True
'IE.StatusBar = True
IE.Visible = True
'WScript.Sleep 2000
Set shl = WScript.CreateObject("WScript.Shell")
shl.SendKeys "% X"
IE.Navigate extracteduri, Nothing, Nothing, postdata, header
Wscript.Quit
Else
Wscript.Echo "Usage: RunURL.vbs <URL to invoke>"
Wscript.Quit
End If
Function Str2Bytes(Text, CharSet)
Const adTypeText = 2
Const adTypeBinary = 1
'Create Stream object
Dim BinaryStream 'As New Stream
Set BinaryStream = CreateObject("ADODB.Stream")
'Specify stream type - we want To save text/string data.
BinaryStream.Type = adTypeText
'Specify charset For the source text (unicode) data.
If Len(CharSet) > 0 Then
BinaryStream.CharSet = CharSet
Else
BinaryStream.CharSet = "us-ascii"
End If
'Open the stream And write text/string data To the object
BinaryStream.Open
BinaryStream.WriteText Text
'Change stream type To binary
BinaryStream.Position = 0
BinaryStream.Type = adTypeBinary
'Ignore first two bytes - sign of
BinaryStream.Position = 0
'Open the stream And get binary data from the object
Str2Bytes = BinaryStream.Read
End Function
I am now using the below function to get the response from the server using https as the protocol and POST as the format but still the server is not able to see the parameter
Set req = CreateObject("MSXML2.ServerXMLHTTP")
'Set the below option to get rid of the "Certificate authority is invalid or
'incorrect, error code - 80072F0D" error
req.setOption 2, 13056
req.open "POST", extracteduri, False
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
encodedParams = Escape(params)
WScript.Echo "encodedParams: " & encodedParams
req.send encodedParams
WScript.Echo "req.responseText: " & req.responseText
Below are the encoded parameters
uui%3DU1%3D123456%26agentid%3D123456
The server still complains that the parameter is missing from the request object.
I am using the same script (XMLHTTP request) but I am encrypting the parameters using the Str2Bytes function (declared above)
Set req = CreateObject("MSXML2.ServerXMLHTTP")
req.setOption 2, 13056
req.open "POST", extracteduri, False
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.send postdata
WScript.Echo "req.responseText: " & req.responseText
I'd recommend using an XMLHTTPRequest instead of the Internet Explorer COM object. See here for an example. Note that you must encode special characters in the post data.
However, if you want to open the URL in IE anyway, you'd probably better stick with your original approach. In that case I'd check the server for more information about why the server side thinks it cannot find the parameter. Does the request even have a parameter named "param1"?
I'm new to QTP and VBScript and I'm trying to get the text file content as a response(sample URL : http://x.x.x.x/dir/MIS/test_667/logfile.667.txt). The below code is working as required on WindowsXP, but getting 'Empty' ResponseText( sIMPResponse = objWinHTTP.ResponseText) on Windows7/Windows2008R2.
I tried with different User-Agent strings # http://www.zytrax.com/tech/web/msie-history.html , but no luck.
Can anyone please assist on the solution to get the .txt file content for WinHTTP.ResponseText.
Thanks in advance for your help.
CodeSnippet:
Dim sResponse, sIMPResponse
Function PortalUrlExists(ByVal sUrl)
On Error Resume Next
UrlExists = False
Dim objWinHTTP, nStatus
'Create a WinHTTP Request using the link's URL
Set objWinHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
If Err.Number <> 0 Then
Exit Function
End If
objWinHTTP.Open "GET", sUrl, False
objWinHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MyApp 1.0; Windows NT 5.1)"
'Send the Request to the Server and capture the response
objWinHTTP.SetTimeouts 180000, 180000, 180000, 180000
objWinHTTP.Send
If Err.Number <> 0 Then
Set objWinHTTP = Nothing
Exit Function
End If
nStatus = objWinHTTP.Status
If nStatus = 200 Then
UrlExists = True
If InStr(1, sUrl, ".txt", vbTextCompare) > 0 Then
sIMPResponse = objWinHTTP.ResponseText ' ***** This is getting "Empty", where as it has to get the text file content from the URL ****
Else sResponse = objWinHTTP.ResponseText
End If
End If
Set objWinHTTP = Nothing
End Function