Post data with https does not get processed at Server side - vbscript

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"?

Related

How can I send http command in vbs [duplicate]

Is there a way to perform an HTTP GET request within a Visual Basic script? I need to get the contents of the response from a particular URL for processing.
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.
The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.
Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).
Here is an example of using XmlHttp to fetch a PDF file and store it:-
Dim oXMLHTTP
Dim oStream
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oXMLHTTP.responseBody
oStream.SaveToFile "c:\somefolder\file.pdf"
oStream.Close
End If
If you are using the GET request to actually SEND data...
check:
http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request
The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.
this explains it:
http://support.microsoft.com/kb/269238
i have had more luck using vbscript to call
set ID = CreateObject("InternetExplorer.Application")
IE.visible = 0
IE.navigate "http://example.com/parser.php?key=" & value & "key2=" & value2
do while IE.Busy....
....and more stuff but just to let the request go thru.
strRequest = "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" " &_
"xmlns:tem=""http://tempuri.org/"">" &_
"<soap:Header/>" &_
"<soap:Body>" &_
"<tem:Authorization>" &_
"<tem:strCC>"&1234123412341234&"</tem:strCC>" &_
"<tem:strEXPMNTH>"&11&"</tem:strEXPMNTH>" &_
"<tem:CVV2>"&123&"</tem:CVV2>" &_
"<tem:strYR>"&23&"</tem:strYR>" &_
"<tem:dblAmount>"&1235&"</tem:dblAmount>" &_
"</tem:Authorization>" &_
"</soap:Body>" &_
"</soap:Envelope>"
EndPointLink = "http://www.trainingrite.net/trainingrite_epaysystem" &_
"/trainingrite_epaysystem/tr_epaysys.asmx"
dim http
set http=createObject("Microsoft.XMLHTTP")
http.open "POST",EndPointLink,false
http.setRequestHeader "Content-Type","text/xml"
msgbox "REQUEST : " & strRequest
http.send strRequest
If http.Status = 200 Then
'msgbox "RESPONSE : " & http.responseXML.xml
msgbox "RESPONSE : " & http.responseText
responseText=http.responseText
else
msgbox "ERRCODE : " & http.status
End If
Call ParseTag(responseText,"AuthorizationResult")
Call CreateXMLEvidence(responseText,strRequest)
'Function to fetch the required message from a TAG
Function ParseTag(ResponseXML,SearchTag)
ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),"</")(0),">")(1)
Msgbox ResponseMessage
End Function
'Function to create XML test evidence files
Function CreateXMLEvidence(ResponseXML,strRequest)
Set fso=createobject("Scripting.FileSystemObject")
Set qfile=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleResponse.xml",2)
Set qfile1=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleReuest.xml",2)
qfile.write ResponseXML
qfile.close
qfile1.write strRequest
qfile1.close
End Function

Using variables with setRequestHeader, why won't they work?

Edit: Problem is solved. For some reason the Base64Encode function was putting a line break in the output string, something I didn't notice until I response.write the output and looked at the source code of the page instead of the compiled page.
I'm trying to send JSON to a remote server in order to get back a JSON response (Basically I send them data, they perform calculations based on my data and send back different data). However instead of getting data back the server tells me the request failed authentication.
The Authentication involves sending a base64 encoded string, username, and password combined. These values can change so I'm using variables to pass the information on. This does not work, however if I enter the fully encoded value as a string it does work.
Function GetAPdataPost(sSendHTML, sURL)
dim apHTTP
dim sHTTPResponse
dim API_KEY
dim API_PWD
dim auth
API_KEY = "fred"
API_PWD = "barney"
auth = Base64Encode(API_KEY & ":" & API_PWD)
Set apHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
apHTTP.Open "POST", sURL, false
apHTTP.setRequestHeader "Content-Type", "application/json; charset=UTF-8"
apHTTP.setRequestHeader "Authorization","Basic ZnJlZDpiYXJuZXk=" '<-- works
apHTTP.setRequestHeader "Authorization", "Basic " & auth '<-- doesn't work
apHTTP.setRequestHeader "Content-Length", len(sSendHTML)
apHTTP.setRequestHeader "Accept", "*/*"
apHTTP.setRequestHeader "Account-Number", "00000004"
apHTTP.setRequestHeader "Cache-Control", "no-cache"
apHTTP.setRequestHeader "Connection", "close"
On Error Resume Next
apHTTP.send sSendHTML
sHTTPResponse = apHTTP.responseText
If Err.Number = 0 Then
GetAPdataPost = sHTTPResponse
Else
GetAPdataPost = "Something went wrong: " & Err.Number
End If
On Error Goto 0
Set apHTTP = Nothing
End Function
Using the first line result in a proper response form the server, a valid JSON string with all the required data. The second line results in a JSON string saying "The request failed authentication".
So aside from typing out the Base64 encoded string how do I get a variable to be recognised as a valid string?
I should just note that I have tried surrounding auth with double quotes ("") and Chr(34) to no avail.
Edit: Base64 Encode function.
Function Base64Encode(sText)
Dim oXML, oNode
Set oXML = CreateObject("Msxml2.DOMDocument.3.0")
Set oNode = oXML.CreateElement("base64")
oNode.dataType = "bin.base64"
oNode.nodeTypedValue =Stream_StringToBinary(sText)
Base64Encode = oNode.text
Set oNode = Nothing
Set oXML = Nothing
End Function
Function Stream_StringToBinary(Text)
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.
BinaryStream.CharSet = "us-ascii"
'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
Stream_StringToBinary = BinaryStream.Read
Set BinaryStream = Nothing
End Function
The Base64Encode function was putting a line break in the output string, something I didn't notice until I response.write the output and looked at the source code of the page instead of the compiled page.
Always remember to look at the raw data, not just the displayed data (i.e. not like me)

setting Preemptive authentication for rest api using vbscript

I am using below code to test Rest API using UFT(VBScript).
url ="http://*********"
username = "test"
Pwd = "pwd"
inputfilepath = "C:\TApps\Message.txt"
Set fso = createobject("Scripting.FileSystemObject")
Set fl = fso.OpenTextFile(inputfilepath)
strMsg = fl.readall
Set f1 = Nothing
fl.Close
Set fso = Nothing
Set restReq = CreateObject("Microsoft.XMLHTTP")
restReq.Open "POST", url, False,username,Pwd
restReq.setRequestHeader "Content-Type","application/json"
'restReq.SetRequestHeader "Authentication", "preemptive"
''restReq.setRequestHeader "PreemptiveAuthentiction",true
restReq.setRequestHeader "Accept","application/json"
restReq.Send strMsg
msgbox restReq.responsetext
I am getting error message as in responseText as
[{"error-code":"1","error_msg":"error when reading the key:null}]
There is no issue with json string as manually I am getting the proper response. After doing some analysis, I came to know 'Preemptive Authentication' should be true for my request. Tried by setting using 'SetRequestHeader', but no luck.

using vbscript to read / save a webpage

goal:
log into the web page
and save the html to a file for parsing later.
the html on the page is just a list of users and when they logged in and off.
When you load the web page up a javascript box pops up and asks for login information
i can fill this with SendKeys but i really want to do this without a window popping up
Set IE = CreateObject("InternetExplorer.Application")
set WshShell = CreateObject("WScript.Shell")
IE.Visible = False ' doesn't set IE page as invisible?????
IE.Navigate "https://mysite/site/console/client-log.jsp"
'how do i fill in the box ???
I'd suggest to use something like Fiddler to identify the request that does the actual login, and then use that information in an XMLHttpRequest.
url = "..."
filename = "..."
Set req = CreateObject("MSXML2.XMLHTTP.6.0")
req.open "POST", url, False
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.send "field1=foo&field2=bar&..."
Set fso = CreateObject("Scripting.FileSystemObject")
fso.OpenTextFile(filename, 2, True).WriteLine req.responseText
If the response is UTF-8 encoded you may need to use an ADODB.Stream object for saving the content.
Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Position = 0
stream.Charset = "utf-8"
stream.WriteText req.responseText
stream.SaveToFile filename, 2
stream.Close

How to download a file using HTTPS connection using VBSCRIPT and by accepting all the certiifcates

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.

Resources