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
Related
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
Getting an error when saving a CSV file (datafeed) from a remote server. It works as expected with some datafeeds but flags an error with others.
The code retrieves the remote datafeed and saves it locally as datafeed.csv
Here is the script so far.
Set xhr = Server.CreateObject("MSXML2.ServerXMLHTTP")
xhr.Open "GET", remote_datafeed, False
xhr.Send
IF NOT xhr.Status = 200 THEN
Response.write"Error retrieving remote CSV file"
else
sResponse = split(xhr.responseText, vbcrlf)
set datafeed = fs.CreateTextFile("files/datafeed.csv", true)
For i = 0 to uBound(sResponse)
datafeed.WriteLine sResponse(i)
Next
Response.write "Remote file has successfully been save locally <br>"
datafeed.close
set datafeed = nothing
I somtimes get an error on the following line.
datafeed.WriteLine sResponse(i)
The error im getting is:
Microsoft VBScript runtime error '800a0005'
Invalid procedure call or argument
After looking throught the remote datafeed, turns out it was to do with utf-8 charset. Changed to the following code solved this issue with utf-8 charset.
Dim objStream
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = 2
objStream.Mode = 3
objStream.Open
objStream.Position = 0
objStream.Charset = "UTF-8"
objStream.WriteText xhr.responseText
objStream.SaveToFile "files/datafeed.csv"
objStream.Close
Set objStream = nothing
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 have a script which is able to download files from the https://mysite.com/xxx.zip but when it goes to a secured link, I want to accept the certificate. There is a huge problem here. I am not able to use "ServicePointManager.ServerCertificateValidationCallback" effectively.
Can anyone please help?
I also have the domain for the certificate site: *.mysite.com
code:
Const scriptVer = "1.0"
Const DownloadDest = "https://mysite.com/xxx.zip"
Const LocalFile = "F:\Testing\xxx.zip"
Const webUser = "admin"
Const webPass = "admin"
Const DownloadType = "binary"
dim strURL
function getit()
dim xmlhttp
set xmlhttp=createobject("MSXML2.XMLHTTP.3.0")
'xmlhttp.SetOption 2, 13056 'If https -> Ignore all SSL errors
strURL = DownloadDest
Wscript.Echo "Download-URL: " & strURL
'For basic auth, use the line below together with user+pass variables above
xmlhttp.Open "GET", strURL, false, WebUser, WebPass
'xmlhttp.Open "GET", strURL, false
xmlhttp.Send
Wscript.Echo "Download-Status: " & xmlhttp.Status & " " & xmlhttp.statusText
If xmlhttp.Status = 200 Then
Dim objStream
set objStream = CreateObject("ADODB.Stream")
objStream.Type = 1 'adTypeBinary
objStream.Open
objStream.Write xmlhttp.responseBody
objStream.SaveToFile LocalFile
objStream.Close
set objStream = Nothing
End If
set xmlhttp=Nothing
End function
'=======================================================================
' End Function Defs, Start Main
'=======================================================================
' Get cmdline params and initialize variables
If Wscript.Arguments.Named.Exists("h") Then
Wscript.Echo "Usage: http-download.vbs"
Wscript.Echo "version " & scriptVer
WScript.Quit(intOK)
End If
getit()
Wscript.Echo "Download Complete. See " & LocalFile & " for success."
Wscript.Quit(intOK)
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
Private Shared Function ValidateCertificate(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) As Boolean
return True
End Function
ServicePointManager is a .NET class, so it can't be used in VBScript. Try this instead:
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.setOption 2, 13056
You must use MSXML2.ServerXMLHTTP here, because MSXML2.XMLHTTP requests don't have the setOption method.
And perhaps you shouldn't broadcast your questions. It's not very polite.