How to fetch Request headers of a GET request from vbscript file - vbscript

HI All I am new in handling http requests and am using UFT and vbscript to achieve the below requirement..I am able to send a GET request in Postman and it has a pre-request script which contains below,
pm.environment.set("hmacCreationTime", new Date().getTime());
and on sending the Get request everytime we get a unique Auth token. Here the value from the pre-request script is passed as a request header.When i try to send get request from UFT(VB script) the request throws "400 bad status" but is working fine in postman with the request headers as below
so i hardcoded the header("timestamp") using setRequestHeader method in my uft script and now i am able to generate the auth token.Please find below code
strWebServiceURL = "https://demo.com/customer/account/v1/auth/getauthtoken"
Set oWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
oWinHttp.SetTimeouts 0, 360000, 360000, 360000
'Open a HTTP connection to a HTTP resource
oWinHttp.Open "GET", strWebServiceURL, False
'owin
oWinHttp.SetRequestHeader "timestamp","1629371122124"
oWinHttp.SetRequestHeader "clientId","clientId"
oWinHttp.SetRequestHeader "User-Agent","neoload"
'oWinHttp.
'Send a HTTP request to the HTTP server with the header and body info
oWinHttp.Send
oWinHttp.WaitForResponse
'Get response
getRestRequest = oWinHttp.ResponseText
Set oWinHttp = Nothing
So i guess the timestamp value from the request Headers are required for the GET request to run successfully and is dynamically fetched from the pre-request script.is there a way to fetch the Request header values from the script ,also i tried getAllresponseheaders(but the timestamp header is not fetched )from UFT script or is there any workaround to achieve this or a way to create the timestamp value in vbscript? Any help to this would be really helpful.Thanks in advance

The following worked fine and can be included in library functions (let me know how it goes for you):
strURLUNPW = "YourWServicesURL,WSUN,WSPW"
msgbox (WebService_GET("YourWServicesURL,WSUN,WSPW")
Public Function WebService_GET(strURLUNPW)
arrURLUNPW = Split(strURLUNPW,",")
strPW = arrURLUNPW(2)
strUN = arrURLUNPW(1)
strURL = arrURLUNPW(0)
WebService_GET = ""
Set objXmlHttpMain = CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttpMain.open "GET",strURL,False,strUN,strPW
objXmlHttpMain.setRequestHeader "Accept", "*/*"
objXmlHttpMain.send strJSONToSend
WebService_GET = objXmlHttpMain.responseText
End Function

Related

Malformed request from aiohttp.ClientSession().post() with multiple image files

I'm still relatively new to Python and my first time to use aiohttp so I'm hoping someone can help spot where my problem is.
I have a function that does the following:
retrieves from the JSON payload two base64 strings - base64Front and base64Back
decode them, save to "images" folder
send the Front.jpg and Back.jpg to an external API
this external API expects a multipart/form-data
imgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())
The response I'm getting is status code 400 with:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}
If I call the url via Postman and send the two jpg files, I get status code 200.
Hope someone can help here.
Thanks in advance.
Try using FormData to construct your request. Remove the content type from header and use it in FormData field as below:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)
Reference: https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file

Power Query call to google.webmaster.api , Post, request problem

I call the google.webmasters.api via Power-Query(M) and managed to configure the oath2 and made my first successfull call to get & list.
Now i try to call the /searchAnalytics/query? which is working only with Post.
This always responds in a 400 error. Formating of the Query or the Url is not working correctly.
Here some additional Infomations:
Power Query - Reference
Google Webmaster Api - Reference
PowerBi Community
format Date different:
body = "{ ""startDate"": ""2019-01-01"", ""endDate"": ""2019-02-02"" }",
to
body = "{ ""startDate"": ""2019/01/01"", ""endDate"": ""2019/02/02"" }",
let
body = "{ ""startDate"": ""2019-01-01"", ""endDate"": ""2019-02-02"" }",
AccessTokenList = List.Buffer(api_token),
access_token = AccessTokenList{0},
AuthKey = "Bearer " & access_token,
url = "https://www.googleapis.com/webmasters/v3/sites/https%3A%2F%2Fxxxxxxxxx.xxx/searchAnalytics/query?",
Response = Web.Contents(url, [Headers=[Authorization=AuthKey, ContentType="application/json", Accept="application/json"], Content=Text.ToBinary(body) ]),
JsonResponse = Json.Document(Response)
in
Response
getting a 400 and is shows as 400 call in Gooogle-Api Overview
Any Ideas whats wrong?
Thx
Ensure request headers are valid. Server expects Content-Type header, not ContentType.
The documentation (https://developers.google.com/webmaster-tools/search-console-api-original/v3/searchanalytics/query#try-it) suggest requests should be something like:
POST https://www.googleapis.com/webmasters/v3/sites/[SITEURL]/searchAnalytics/query HTTP/1.1
Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
Content-Type: application/json
{}
So seems like main takeaways are:
HTTP POST method must be used
Web.Contents documentation (https://learn.microsoft.com/en-us/powerquery-m/web-contents) suggests including the Content field in the options record to change request from GET to POST.
URL must be valid
You haven't provided your actual URL, so you'll have to validate it for yourself. I would get rid of the trailing ? in your url (as you aren't including a query string -- and even if you were, you should pass them to the Query field of the options record instead of building the query string yourself).
Headers (Authorization, Accept, Content-Type) should be valid/present.
Build your headers in a separation expression. Then pass that expression to the Headers field of the options record. This gives you the chance to review/inspect your headers (to ensure they are as intended).
Body should contain valid JSON to pass to the API method.
Creating valid JSON via manual string concatenation is liable to error. Using Json.FromValue (https://learn.microsoft.com/en-us/powerquery-m/json-fromvalue) seems a better approach.
All in all, your M code might look something like:
let
// Some other code is needed here, in which you define the expression api_token
AccessTokenList = List.Buffer(api_token),
access_token = AccessTokenList{0},
AuthKey = "Bearer " & access_token,
requestHeaders = [Authorization = AuthKey, #"Content-Type" = "application/json", Accept = "application/json"],
parametersToPost = [startDate = "2019-01-01", endDate = "2019-02-02"], // Can include other parameters here e.g. dimensions, as mentioned in Search Console API documentaton.
jsonToPost = Json.FromValue(parametersToPost, TextEncoding.Utf8), // Second argument not required (as is default), but just be explicit until you've got everything working.
url = "https://www.googleapis.com/webmasters/v3/sites/https%3A%2F%2Fxxxxxxxxx.xxx/searchAnalytics/query", // Uri.EscapeDataString function can be use for URL encoding
response = Web.Contents(url, [Headers=requestHeaders, Content=jsonToPost])
in
response
Untested (as I don't have an account or API credentials).

How to get grafana alerts in ruby

I am trying to use the grafana api (doc here http://docs.grafana.org/http_api/alerting/) to get the list of all the alerts in grafana.
Here's what I tried:
uri = URI("http://example:3000")
headers = {
'Authorization'=>'Bearer test',
'Content-Type' =>'application/json',
'Accept'=>'application/json'
}
http = Net::HTTP.new(uri.host, uri.port)
request1 = Net::HTTP::Get.new("/api/dashboards/uid/uKH1CKVmk")
response1 = JSON.parse(http.request(request1).body)
This one works, it returns the json of the dashboard, but when I try :
request2 = Net::HTTP::Get.new("/api/alerts?state=ALL") or
request2 = Net::HTTP::Get.new("/api/alerts?dashboardId="+response1["id"].to_s+"")
request2['Authorization'] = "Bearer test"
request2['Content-Type'] = "application/json"
request2['Accept'] = "application/json"
I get an empty json.
Any ideas what I am doing wrong ?
Thanks,
Nicu
Found the problem, when I created the API token I selected "Viewer" permissions, I was thinking its enough to just make a get request on alerts, but apparently it is not, made a new API token with "Admin" permissions and it works.

How can I output the response from one VBS file to a text file or a UIPath variable?

I have written some simple VBScript code to use a GET REST HTTP request. It is as follows:
endpoint="somethingsomething"
parameter ="?someparameters&sysparm_limit=10000"
Set objXmlHttpMain = CreateObject("Msxml2.ServerXMLHTTP.6.0")
URL = endpoint & resource & parameter
On Error Resume Next
objXmlHttpMain.open "GET",URL, False, "admin", "jhdsjkF"
objXmlHttpMain.setRequestHeader "Content-Type", "application/xml"
objXmlHttpMain.setRequestHeader "Accept", "application/xml"
objXmlHttpMain.setRequestHeader "UserID", "admin"
objXmlHttpMain.setRequestHeader "Password", "jhdsjkF"
objXmlHttpMain.send
response = objXmlHttpMain.responsetext
Ideally, I want to store this response in a UIPath string variable to use it further in the sequence. Is there a way to do that?
However, if there isn't could you assist me in putting this response in a text file? I want the text file to be the same no matter how many times the VBScript is executed, and for the response to be written after the file gets cleared.
I'm not sure why ...
uipath = response
or
uipath = objXmlHttpMain.responsetext

POST Request using VBScript

Am trying to post a request and get a response through VBS.
Dim response
Set xHttp = CreateObject("Microsoft.XMLHTTP")
xHttp.Open "POST", "https://idoc-api-int.platform-test.sample.com/interactiveDocumentOrchestrator", False, u1i, p1i
xHttp.Send
response = xHttp.responseText
Msgbox response
Basically, I'm using SOAP UI to send a request to the URL with a body content and I will be getting the response. I'm trying to achieve it through a VBScript. Kindly suggest if there is any way I am able to do this.

Resources