Send Body and Params XMLHTTP [duplicate] - vbscript

This question already has an answer here:
How to POST JSON Data via HTTP API using VBScript?
(1 answer)
Closed 14 days ago.
I have a script ready in Postman, but I can't export it to VBSCRIPT because in postman it has Body with JSON and Params (path Variables) with KEY and VALUE. How to include both information in XMLHTTP POST? O God!
EndPointLink = "http://localhost:8080/sessions/addcard"
set http=CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.open "POST",EndPointLink
'Body
strDataRaw = "{""id"":""55119"",""type"":""number"",""message"":{""text"":""Hello""}}"
http.setRequestHeader "Content-Type","application/json"
http.setRequestHeader "sessionId=Super"
http.send strDataRaw
This script works very well. But now, I need to pass two parameters, which already worked in Postman, but I don't know how to add them to this script.
'Params Path Variables Postman Key and Value:
Key="sessionId"
Value="2021"
Description="Session ID"
Or Only: "SessionId" = "2021"
How to add the parameters together with the Body or separately? I don't know. Can someone write this solution?
Asp Classic and Vbscript
Thanks and Best Regards.
The script without the "SessionID" from error.
{
"error": "Session not found"
}

As far as I know there is no native JSON support in vbscript, you can just concatenate your variables into a json string.
Key="sessionId"
Value="2021"
Description="Session ID"
strDataRaw = "{""key"":""" & Key & """,""value"":""" & Value & """,""description"":""" & Description & """,""id"":""55119"",""type"":""number"",""message"":{""text"":""Hello""}}"

Related

how save value in string variable by Javascript executor in jmeter web sampler

Hi I want to store the value return by below code in JMeter webDriver Sampler . but i am getting error.
String access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
OR
var access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
Both above ways are not working?
In order to be able to help we need to know the details of the error "you are getting". Also it's unclear what localStorage.key(2) object stands for.
Here is an example of getting se:fkey value from https://stackoverflow.com website:
I used default language for WebDriver Sampler: javascript and the following piece of code:
WDS.sampleResult.sampleStart()
WDS.browser.get('https://stackoverflow.com')
var access_token = WDS.browser.executeScript('return window.localStorage.getItem("se:fkey")')
WDS.log.info('Got the following value from local storage: ' + access_token)
WDS.sampleResult.sampleEnd()
And it works just fine:
If you additionally need to store the value into a JMeter Variable add the following line:
WDS.vars.put('access_token', access_token)
and you will be able to access the extracted value as ${access_token} where required.
More information: The WebDriver Sampler: Your Top 10 Questions Answered

Passing a subscription key as a request header with msxml2.ServerXMLHTTP - Classic ASP/VB

I'm trying to pull data from an NHS API using a little bit of classic ASP (all I know I'm afraid) but am struggling to successfully pass the subscription key to the API.
The instructions are as follows:
Pick a page on the NHS website, for example: https://www.nhs.uk/conditions/acne.
Make a note of the path, for example: conditions/acne.
Using a tool such as curl, Postman or your web browser, make a GET request to https://api.nhs.uk/content/acne with a valid subscription key subscription‑key: {subscription-key} in the request header.
You’ll receive a JSON response structured using schema.org and the fields for this are explained in the following documentation....
From https://developer.api.nhs.uk/documentation/content-api
So, I wrote the following...
<%
Set xml = Server.CreateObject("MSXML2.ServerXMLHTTP")
xml.Open "GET", "https://api.nhs.uk/conditions/abdominal-aortic-aneurysm-screening/", False
on error resume next
xml.setRequestHeader "subscription‑key", "MY-API-KEY-HERE"
xml.setRequestHeader "Content-Type", "application/json"
xml.setRequestHeader "Accept", "application/json"
xml.Send
Response.Write "<h1>The HTML text</h1><xmp>"
Response.Write xml.responseText
Set xml = Nothing
%>
This just gives me the following response:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
They have example scripts in 5 different languages but not ASP or even ASP.NET
Any ideas what I can try to get this working?
Thanks
EDIT
Trying the method suggested here How can I post data using cURL in asp classic? ...
<%
Dim http: Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
Dim url: url = "https://api.nhs.uk/conditions/abdominal-aortic-aneurysm-screening/"
'Dim data: data = "something=this" - took this out as its a querystring for POST
With http
Call .Open("GET", url, False)
'Call .SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
Call .SetRequestHeader("subscription‑key", "MY-API-KEY-HERE")
'Call .Send(data) <- the data was the querystring, so not relevant here
Call .Send()
End With
If Left(http.Status, 1) = 2 Then
'Request succeeded with a HTTP 2xx response, do something...
Else
'Output error
Call Response.Write("Server returned: " & http.Status & " " & http.StatusText)
End If
%>
This gives me Invalid procedure call or argument: 'SetRequestHeader'
EDIT WITH SOLUTION
Working code with hyphen issue fixed...
<%
Dim http: Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
Dim url: url = "https://api.nhs.uk/conditions/abdominal-aortic-aneurysm-screening/"
With http
Call .Open("GET", url, False)
Call .SetRequestHeader("subscription-key", "MYKEYHERE")
Call .Send()
End With
If Left(http.Status, 1) = 2 Then
'Request succeeded with a HTTP 2xx response, do something...
Response.Write http.responseText
Else
'Output error
Call Response.Write("Server returned: " & http.Status & " " & http.StatusText)
End If
%>
Thanks Lankymart!
Tried your take on the duplicate example and it returned
Invalid procedure call or argument: 'SetRequestHeader'
This puzzled me as that code had been tested before and work fine so what changed?
So I dug into the SetRequestHeader method calls.
Turns out the error only occurs on this line;
Call .SetRequestHeader("subscription‑key", "MY-API-KEY-HERE")
In the end, removed subscription‑ from the header name and it worked without causing a compilation error.
That led me to check the hyphen in the code using Asc("‑") and comparing that with a standard hyphen and sure enough they are different.
<%
Response.Write Asc("‑") & "<br />" 'From the code
Response.Write Asc("-") & "<br />" 'Standard hyphen
%>
Output:
-15454
45
Replaced the character with a standard hyphen the error has gone and the code runs returning;
Server returned: 401 Unauthorized

Classic ASP XMLHttp Send very slow

I've inherited a classic asp project and as part of the upgrade process we're moving a lot of the business logic to a REST API (WebApi 2.2)
The authorization endpoint for the api is written, and the asp site can call it, but it's very slow compared with calling directly via Postman.
(I'm a C# coder not a VBScript one so the below code may be offensive)
Asp Code:
' Send a prebuilt HTTP request and handle the response
' Returns true if the request returns a 200 response, False otherwise
' Response body is placed in Response
' ErrorMessage is set to return status text if an error code is returned
Function HandleRequest(ByRef objRequest, strBody)
set profiler = Server.CreateObject("Softwing.Profiler")
HandleRequest = False
' Add auth token if we have it
If Not m_accessToken&"" = "" Then
objRequest.SetRequestHeader "Authorization", "Bearer " & m_accessToken
End If
' Originating IP for proxy forwarding
If Not m_clientIp&"" = "" Then
objRequest.SetRequestHeader "X-Forwarded-For", m_clientIp
End If
On Error Resume Next
If (strBody&"" = "") Then
objRequest.Send()
Else
profiler.ProfileStart()
objRequest.Send(strBody)
flSendRequest = profiler.ProfileStop()
End If
If Err.Number = 0 Then
Dim jsonResponse
If (objRequest.ResponseText&"" <> "") Then
profiler.ProfileStart()
set jsonResponse = JSON.parse(objRequest.ResponseText)
flJson = profiler.ProfileStop()
set m_Response = jsonResponse
End If
If objRequest.Status = 200 Then
HandleRequest = True
m_errorMessage = ""
Else
m_errorMessage = objRequest.statusText
End If
Else
m_errorMessage = "Unable to connect to Api server"
End If
On Error GoTo 0
End Function
You can see there's some profiling code in there.
The following post request takes 392ms
POST localhost:5000/oauth/token
Content-Type application/x-www-form-urlencoded
client_id:ABCDEF0-ABCD-ABCD-ABCD-ABCDEF-ABCDEF01234
client_secret:aBcDeF0123456789aBcDeF0123456789=
username:demo
password:demo
grant_type:password
If I issue the same request direct to the Api via Postman it takes 30ms.
That's more than 13x slower.
What gives?
Edit
Raw result from Softwing Profiler:
flJson 10.9583865754112
flSendRequest 392.282022557137
So after a lengthy-ish discussion with the #J-Tolley it looks as though the issue is with the Softwing.Profiler documentation which states;
all results are given in milliseconds
even though earlier in the page it states;
has a ten milliseconds resolution
Have not used the Softwing.Profiler component alone before and would recommend anyone using in a Classic ASP environment to implement it using the SlTiming class library provided by 4GuysFromRolla.
In that article it even warns anyone using the Softwing.Profiler ProfileStop() method to;
Be aware that Softwing.Profiler's ProfileStop method returns a value in ticks (tenths of milliseconds).

MSXML2.ServerXMLHTTP and national characters

This question is related to this one: Character encoding Microsoft.XmlHttp in Vbscript, but differs in one thing, the national characters are in the domain name, not only arguments.
The task is: download a page from the given URL.
I already solved problem of passing UTF8 string into VBScript by reading it from UTF8 encoded file through ADO.
But now when I try opening it MSXML2.ServerXMLHTTP returns error: The URL is invalid.
Here is VBScript code:
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("fileWithURL.txt")
url = objStream.ReadText()
objStream.Close
Set XMLHttpReq = CreateObject("MSXML2.ServerXMLHTTP")
XMLHttpReq.Open "GET", url, False
XMLHttpReq.send
WEBPAGE = XMLHttpReq.responseText
If you put something like hxxp://россия.рф/main/page5.html into the UTF8 encoded fileWithURL.txt the script will raise an error while working ok with hxxp://google.com.
The workaround is to use ascii representation of the domain name - but I yet haven't found PunnyCode encoder for vbscript (apart from Chillkat which is an overkill for my task).
Will appreciate your help on the main problem or workaround.
I've made an amazing journey in to depth of my hard drive and found a code writen by / for Jesper Høy. This was the source code of SimpleDNS Plus' IDN Conversion Tool at that time.
Archive.org page snapshot: http://www.simpledns.com/idn-convert.asp
Archive.org file snapshot: idn-convert-asp.zip
You can also copy the whole code from this gist.
Create a function to convert URLs.
Function DummyPuny(ByVal url)
Dim rSegments : rSegments = Split(url, "/")
If UBound(rSegments) > 1 Then
rSegments(2) = DomainPunyEncode(rSegments(2))
End If
DummyPuny = Join(rSegments, "/")
End Function
Then convert your url before making the request.
XMLHttpReq.Open "GET", DummyPuny(url), False

Post data from VBscript

I have a function that need to accept two parameters- user and folder! I call that function from VBscript, and parameters need to be send with post method. This is the Vbscript function code from where I want to post data:
Sub loadDocument()
Const HOST = "http://192.168.0.144/webservice13/service1.asmx/Lock?User="& PC\User & "folder="&c:\foldername
Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
xmlhttp.open "POST",HOST
xmlhttp.send ""
End Sub
Now when i try to execute this function i getting error message that i have syntax error!
I assume that error is in this line:
Const HOST = "http://192.168.0.144/webservice13/service1.asmx/Lock?User="& PC\User & "folder="&c:\foldername
How I can resolve this, how i can post two variables to this function?
Thanks!
I think you cannot declare a Const variable with variable parts. Change the line to
dim userVar, folderVar, HOST
userVar = "PC\User"
folderVar = "c:\foldername"
HOST = "http://192.168.0.144/webservice13/service1.asmx/Lock?User=" & userVar & "&folder=" & folderVar
Have you made sure the PC\User and c:\foldername paremeters you are using when constructing your HOST variable are propery URL Encoded?
You should also prepend an & to any additional parameter. You have not done this with your "folder=" paramenter, which should be "&folder=".

Resources