xmlHTTPRequest vs. WinHTTPRequest- What killer advantages does the xmlRequest have?

xmlHTTPRequestIn this video I walk through both the xmlHTTPRequest and the WinHTTPRequest.  As I mention in the video, Jackie Sztuk and I have a great  AutoHotkey webinar on Intro to API calls.  I also have several examples on my API page.

I also mention using Fiddler to monitor the browser traffic and grab your cookies / headers.

WinHTTPRequest vs. xmlHTTPRequest tutorial


Here’s the syntax I used for the WinHTTPRequest example

WinHTTPRequest syntax

And here’s the corresponding two XML API calls I demonstrated in the video

xmlHTTPRequest example using Msxml2.XMLHTTP COM object

Here’s the example connecting to the IE page and sending the API request with the xmlHTTPRequest()

API Call with AutoHotkey to pull WordPress Statistics

I stumbled upon something I had worked on years ago to pull stats from WordPress and decided to have a little fun. In this script I show how you can perform API calls with AutoHotkey to extract your stats from WordPress.

API Call with AutoHotkey to pull WordPress Statistics

API Call with AutoHotkey to pull WordPress Statistics


#SingleInstance,Force
Blog_URI:="https://the-Automator.com" ;note, even if WordPress is in another folder, use this
IniRead, API_Key,Auth.ini,API, Key ;API Key is your key to Akismet

;*******************************************************
;*********Make sure you have not turned-off your API access in WordPress!******
;~ some documentation here: https://stats.wordpress.com/csv.php
;~ period = days,week,month
;~ limit = deault is 100 -1 is unlimitedIniRead, API_Token ,Auth.ini,API, Token
;~ table = One of views, postviews, referrers, referrers_grouped, searchterms, clicks, videoplays.
;********************Views***********************************
If (){
oAHK:=API_Call({"api_key":api_key,"blog_uri":Blog_URI,"table":"views","period":"days","format":"json"})
data:="Views`tDate`n"
for k, v in oAHK
data.=v.views "`t" v.date "`n"
LV_Table(Clipboard:=data,delimiter:="`t",UseHeader:=1,Title:="Views")
}

;********************Refererrs***********************************
If (0){
oAHK:=API_Call({"api_key":api_key,"blog_uri":Blog_URI,"table":"referrers","period":"month","days":"-1","format":"json"})
data:="Views`tReferrers`n"
for k, v in oAHK.1.referrers
data.=v.views "`t" v.referrer "`n"
LV_Table(Clipboard:=data,delimiter:="`t",UseHeader:=1,Title:="Search terms")
}

;********************clicks***********************************
If (0){
oAHK:=API_Call({"api_key":api_key,"blog_uri":Blog_URI,"table":"clicks","period":"month","days":"30","format":"json"}) ;,"summarize":""
data:="Clicks`tURL`n"
for a, b in oAHK
for c,d in b.clicks
data.=d.views "`t" d.click "`n"
LV_Table(Clipboard:=data, delimiter:="`t",UseHeader:=1,Title:="Clicks") ;Still need to aggregate numbers
}
;********************Search***********************************
If (1){
oAHK:=API_Call({"api_key":api_key,"blog_uri":Blog_URI,"table":"searchterms","period":"month","days":"-1","format":"json"})
data:="Views`tSearch Terms`n"
for k, v in oAHK
for a,b in v.SearchTerms{
if (b.SearchTerm !="encrypted_search_terms")
data.=b.views "`t" b.searchterm "`n"
}
LV_Table(Clipboard:=data,delimiter:="`t",UseHeader:=1,Title:="Search terms")
}

;********************API Call***********************************
API_Call(QS){
QS:=QSB(QS)
HTTP := ComObjCreate("WinHttp.WinHttpRequest.5.1") ;Create COM Object
HTTP.Open("GET","http://stats.wordpress.com/csv.php" QS ) ; "&summarize" this will return summary of metric
HTTP.SetRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
HTTP.Send() ;If POST request put data in "Payload" variable
oAHK:=ParseJSON(HTTP.ResponseText) ;Make sure the ParseJSON function is in your library
return oAHK
}
;********************Query String Builder***********************************
QSB(x){
for a,b in x
String.=(A_Index=1?"?":"&") a "=" b
return String
}

;********************Shove inot List View***********************************
LV_Table(Data_Source, delimiter="`t",UseHeader=1,Title=""){ ; default delimiter set to tab
if FileExist(Data_Source) ;if file exists use it as source
FileRead, Data_Source, %Data_Source% ;read in and store as variable

;***********parse the data in variable and store in object*******************
data_obj := StrSplit(Data_Source,"`n","`r") ;parse earch row and store in object
rowHeader:=StrReplace(data_obj.RemoveAt(1),Delimiter,"|",Numb_Columns) ; Remove header from Object and convert to pipe delimited
if (useHeader=0){
loop, % Numb_Columns+1
RH.="Col_" A_Index "|"
rowHeader:=RH
}

dCols:= (Numb_Columns<8) ? 400: ((Numb_Columns<80) ? 650 : 1100) ;if cols <10 use 400; if cols <80 use 650 ; else use 1100
dRows:= (data_obj.MaxIndex() >27) ? 26 : data_obj.MaxIndex() ;if rows >27 use 26 else use # of rows

Gui, Table_View: New,,%Title% ;create new gui window and set title
Gui, Add, ListView, w%dCols% r%dRows% grid , % rowHeader ;set headers

For Each, Row In data_obj ;add the data lines to the ListView
LV_Add("", StrSplit(Row, Delimiter)*) ;LV_Add is a variadic function

Gui, Table_View:Show
}

;********************Maestrit Parse JSON***********************************
ParseJSON(jsonStr){
static SC:=ComObjCreate("ScriptControl"),C:=Chr(125)
SC.Language:="JScript",ComObjError(0),SC.ExecuteStatement("function arrangeForAhkTraversing(obj){if(obj instanceof Array){for(var i=0; i }ConvertJScriptObjToAhks(JSObj){
if(JSObj[0]="Object"){
Obj:=[],Keys:=JSObj[1][0],Values:=JSObj[1][1]
while(A_Index<=Keys.length)
Obj[Keys[A_Index-1]]:=ConvertJScriptObjToAhks(Values[A_Index-1])
return Obj
}else if(JSObj[0]="Array"){
Array:=[]
while(A_Index<=JSObj[1].length)
Array.Push(ConvertJScriptObjToAhks(JSObj[1][A_Index-1]))
return Array
}else
return JSObj[1]
}


How I used Google Translate to save the client both time and money

In this session of “what I’ve automated with AutoHotkey” I explain how I saved my client a ton of time and money by using the Google Translate API.

How I used Google Translate to save the client both time and money

Below is the code I used in the code to Google Translate to save the client both time and money.  Make sure you put my Excel function library and Maestrith’s Notify function in your library.

#SingleInstance,Force
Global API_Key,ID,All,From,To,XL,EndPoint,LangObj
Global Column_to_Translate:="A", Column_To_Put_Translations:="B"
;**************************************
EndPoint:="https://www.googleapis.com/language/translate/v2" ; ?parameters
IniRead, API_Key,Auth.ini,API, Key ;read current token (You'll need to get your own)

XL:=XL_Handle(1)
if ! IsObject(Xl) { ;Joe added 9/22 to make sure Excel is loaded before running
  MsgBox % "Please Start Excel then click this box"
  Reload
}

LangObj:={"Chinese Trad":"zh-CN","Chinese Simp":"zh-TW",Italian:"it",Czech:"cs",French:"fr",German:"de",Hebrew:"he",Indonesian:"id",Japanese:"ja",Korean:"ko",Malay:"ms",Polish:"pl",Portuguese:"pt",Russian:"ru",Spanish:"es",Thai:"th",Turkish:"tr",Vietnamese:"vi",English:"en"}
for a in LangObj ;Build Language object for ComboBox
  LangList.=a "|"

All:=[]
gui,+hwndMain
ID:="ahk_id" Main
gui,Add,ListView,w800 h300,Text
gui,Add,ComboBox,vFrom,% Trim(LangList,"|") ;~ https://cloud.google.com/translate/docs/languages
gui,Add,ComboBox,x+m vTo,en||it|es|la ;Languages to translate into
gui,Add,Text,x+60, Column to be translated 
gui,Add,ComboBox,x+m w50 vColumn_to_Translate,A||B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z  ;Store which column to translate
gui,Add,Text,x+60, Destination for translations
gui,Add,ComboBox,x+m w50 vColumn_To_Put_Translations,A|B||C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z ;Store where to put the translations
gui,Add,Button,xm gLang,Discover Language 
gui,Add,Button,x+25 gTranslate,Translate
gui,Add,Button,xm gRefresh,Refresh
Refresh()
gui,Show
return

Refresh(){
  Rows:=XL.ActiveSheet.UsedRange.Rows.Count,LV_Delete(),All:=[]
  while(A_Index<=Rows){
    if(Value:=(Obj:=XL.Range(Column_to_Translate . A_Index)).Value)
      All.Push(Obj),LV_Add("",Value)
    if(All.MaxIndex()=15)
      Break
  }LV_Modify(1,"Select Vis Focus")
}
Translate(){
  Gui,Submit,NoHide
  From:=LangObj[From]?LangObj[From]:From
  if(!From||!To)
    return m("Both Language values must be set")
  XL.Columns(Column_To_Put_Translations).ColumnWidth:=100
  Rows:=XL.ActiveSheet.UsedRange.Rows.Count
  Blank:=0,BlankInput:=0
  while(A_Index<=Rows){
    if(!(Obj:=XL.Range(Column_To_Put_Translations . A_Index)).Value){
      Blank:=0
      t("Processing")
      if(Value:=XL.Range(Column_to_Translate . A_Index).Value){
        QueryString:=QueryString_Builder({"source":From,"target":To,"q":Value,"key":API_Key})
        RegExMatch(Val:=API_Call(EndPoint,queryString),"OUi)\x22translatedText\x22:\s+\x22(.*)\x22",Found)
        Text:=Found.1
        while(RegExMatch(Text,"OU)(\&#(\d+);)",Found))
          Text:=RegExReplace(Text,"\Q" Found.1 "\E",Chr(Found.2))
        while(RegExMatch(Text,"OU)(\&quot;)",Found))
          Text:=RegExReplace(Text,"\Q&quot;\E",Chr(34))
        Obj.Value:=Text
      }
    }else{
      Blank++
      m(Blank)
      if(Blank=5)
        Break
    }
  }
  t(),Notify(60).AddWindow("Complete",{size:14,Animate:"Center",ShowDelay:1000,Icon:161,IconSize:15,Title:"Translations",TitleSize:14,Color:"0x00FF00",TitleColor:"0xFF0000",time:6000})
}
GuiEscape:
GuiClose:
ExitApp
return
;********************Language detection***********************************
Lang(){
  Lang:=API_Call("https://translation.googleapis.com/language/translate/v2/detect",QueryString_Builder({q:All[LV_GetNext()].Value,key:API_Key}))
  RegExMatch(Lang,"OUi)\x22language\x22:\s+\x22(.*)\x22",Found)
  for a,b in LangObj
    if(b=Found.1)
      Language:=a
  ControlSetText,ComboBox1,% Language?Language:Found.1,%ID%
}
;********************API Call***********************************
API_Call(EndPoint,queryString){
  static WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
  WebRequest.Open("GET", EndPoint . queryString)
  WebRequest.SetRequestHeader("Accept", "text/xml;charset=UTF-8")
  WebRequest.Send()
  return Response:=WebRequest.ResponseText
}
;********************URI Encode charachters***********************************
UriEncode(Uri, full = 0){
  oSC := ComObjCreate("ScriptControl")
  oSC.Language := "JScript"
  Script := "var Encoded = encodeURIComponent(""" . Uri . """)"
  oSC.ExecuteStatement(Script)
  encoded := oSC.Eval("Encoded")
  Return encoded
}

 

Connecting to an IE window to send API calls (XMLHTTP Requests)

In the below AutoHotkey Podcast we discussed how to send API calls from an active IE window.  A subscriber asked me to share the code so below is the example code I mentioned in the recording

Connecting to active IE window and sending an API call

Payload={"filter":{"acctId":"44XXXX","serviceId":[],"msgFormat":[],"status":[1,2,192],"received":{"From":"1970-01-01T00:00:00.000Z","To":"1970-01-01T00:00:00.000Z"},"modified":{"From":"1970-01-01T00:00:00.000Z","To":"1970-01-01T00:00:00.000Z"},"originator":"","threadId":[],"eTo":[],"excludeMessages":[],"extraSql":"AND msg.thread_id IS NULL"},"options":{"doNotCallFlag":true,"contactId":true,"deepContactIdSearch":true,"offset":0,"limit":0,"orderColumn":"\"tdsReceived\"","orderDirection":"DESC"}}

oWindow := ComObject(9, ComObjQuery(WBGet(), "{332C4427-26CB-11D0-B483-00C04FD90119}", "{332C4427-26CB-11D0-B483-00C04FD90119}"), 1)
MsgBox % IsObject(oWindow)

msgbox % oWindow.title
xhr := oWindow.XMLHttpRequest()
xhr.open("POST", "https://800link.com/WebService/SSL/I800LinkVmMsgs.asmx/Load",1)
xhr.setRequestHeader("Content-Type", "application/json")
xhr.send(Payload)
while(xhr.ReadyState!=4) ;Wait for it to complete
  Sleep,50
msgbox % "response: " xhr.response
msgbox % "body: " xhr.responseBody
msgbox % "status: " xhr.Status