I am connecting to an API using xmlhttp in VBA. The problem is that I need to create a loop multiple times using the same API link with the only difference that I send different JSON string.
Is it possible to open the connection and send headers and authentification only once then send data and receive response multiple times?
The main purpose is to improve the speed of the code. I am aware that I can send header and authenticate inside the loop but it runs too slow for my needs.
Thank you!
APIKey = "xx"
Session = "ss"
API_Link = "zz"
Dim xhr: Set xhr = CreateObject("MSXML2.XMLHTTP")
With xhr
.Open "POST", API_Link, False
.setRequestHeader "X-Application", APIKey
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Authentication", Session
End With
For Each cl In Rng
'The below runs only the first time then it gives an error
xhr.send JSON_Query
a = xhr.ResponseText
next cl
No, I don't believe you can with xmlhttp (happy to be proven wrong) in terms of keeping headers. The best you can do is create the xmlhttp object outside the loop and hold certain values in variables for re-use. You still have to provide the transactions of .Get , .Send and the headers.
In terms of preserving authentication I think you can login once and then pass the cookies (JSESSION) in subsequent requests - depending on expiration period - using MSXML2.ServerXMLHTTP.
In other languages e.g. python you have the implementation of http sessions. This allows you to persist certain parameters across requests.
HTTP Persistent Connection
In python, for example:
So, you create the
Session
object, which has the same methods as the API library which issues the requests (like xmlhttp does) and then update headers which persist.A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies Srinivas Balasani
Advantages:
Disadvantages:
So, still using python example, we commonly use a
with
statement which automatically ensures closure of connection with an exit method after execution of the code block nested within.I think WinHttp has functionality around setting cookies. Additional session info here. Whilst there is mention of pointers to string
lpszHeaders
:this is not something I have ever tried.