Error handling with XMLHTTP on link not existing - excel

I use XMLHTTP to connect to a API of a webserver and retrieve some data.
I connect to a http url so I can access from every position, but I want to do that when I am in office, if there is no internet connection, the macro is continuing to working connecting to a second url (internal IP).
I was thinking something like that:
Dim basic_url, basic_url_web, basic_url_local As String
basic_url_web = "www.notexistingurl.com"
basic_url_local = "192.168.178.3"
Dim myurl As String
On Error Resume Next
myurl = basic_url_web + "/api/product/read_product.php?id=4"
xmlhttp.Open "GET", myurl, False
xmlhttp.Send
If Err.Number <> 0 then
myurl = basic_url_local + "/api/product/read_product.php?id=4"
xmlhttp.Open "GET", myurl, False
xmlhttp.Send
END IF
On Error GoTo 0 'error checkin restored
But it is not working, actually when I call the xmlhttp.Send function I ever have a -2147467259 error number, and this is the same error number I have if actually there is no error.
If I don't use the "On Error Resume Next", then I have automation error on the .send() function (on an inexistent link), and therefore I cannot work with it.
I'm becoming crazy, I took about only 2-3 hours to do all the connection with the API and everything was working perfectly, but now I'm working since days to find a solution to have a second URL if the first cannot be reached.
Thank you for your suggestions

Related

How to use the MSXML2.XMLHTTP object outside VPN?

I have coded these few lines below. The code correctly works when I connect through a VPN but no longer works outside VPN. The returned status code is 12007 out VPN and 200 with the VPN.
For example, you can use myUrl : "https://www.boursedirect.fr/fr/marche/euronext-paris/lyxor-ep-na-us-LU1832418856-MUA-EUR-XPAR/seance"
Do you have any idea how to resolve this difficulty?
Public Function InterrogationCours(myUrl) As Double
Dim avant as String, apres as String, cotation As String
avant = "quotation-last bd-streaming-select-value-last"
apres = "</span"
On Error Resume Next
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", myUrl, False
.Send
Debug.Print .Status
If .Status = 200 Then cotation = Split(Split(Split(.responseText, avant)(1), ">")(1), apres)(0)
End With
InterrogationCours = Nettoyage(cotation)
End Function

WinHttpRequest fails with automation error but XMLHTTP60 works

I've been doing quite a bit of web scraping over the past year and at some point, for reasons I don't remember anymore, I decided to use the Microsoft WinHTTP Services version 5.1 library as my default solution when sending HTTP requests.
I've never had any problems with it and I have achieved anything I ever attempted to do as far as web scraping is concerned.
That is, until i tried the following:
Sub nse()
Dim req As New WinHttpRequest
Dim url As String, requestPayload As String
url = "https://www.niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString"
requestPayload = "{'name':'NIFTY 50','startDate':'01-Feb-2020','endDate':'01-Feb-2020'}"
With req
.Open "POST", url, False
.setRequestHeader "Content-Type", "application/json; charset=UTF-8"
.send requestPayload
Debug.Print .responseText
End With
End Sub
The .send method fails with a
Run-time error -2147012894 (80072ee2) Automation error
Changing to Dim req As New MSXML2.XMLHTTP60 solves the issue completely.
What am I missing here? Could it be website specific somehow? Is there something in the inner workings of these 2 libraries I should know?
Any input would be appreciated.

POST api authentication in vba

I am trying to connect excel (through vba) to the "teamleader" api v1, via post calls.
api docs here
I tried some solutions which I have found, regarding post calls in vba, but seem to be getting nowhere.
This is what I have so far:
Sub test2()
Dim url As String
Dim objhttp As Object
Set objhttp = CreateObject("MSXML2.ServerXMLHTTP")
url = "https://app.teamleader.eu/api/helloWorld.php"
With objhttp
.Open "POST", url, False
.setRequestHeader "api_group", "xxx"
.setRequestHeader "api_secret", "xxx"
.send
Debug.Print .responseText
End With
End Sub
This however gives me this response:
{"status":"failed","reason":"Please set api_group."}
Does anyone have any idea how to get this to work?
Turns out I needed the put all the authentication in the url itself, this question can be closed.

Operation timed out in xmlhttp.Send in VBA

I am fetching data from website. It was working my laptop till last week without any trouble anytime, All of the sudden, it started to give strange behavior(It works in evening and it fail to work during day time. Can anyone please look into below sample code and let me know the reason?
Sub FailedTest2()
Dim xmlhttp As Object
'Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.6.0") ' I tried this also
URL = "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?underlying=HDFCBANK&instrument=FUTSTK&expiry=26DEC2019"
xmlhttp.Open "GET", URL, False
xmlhttp.setRequestHeader "Content-Type", "text/JSON"
xmlhttp.Send
MsgBox xmlhttp.responseText
End Sub

Excel Web Query Object and Cookies: Is there a better way?

I have a HTML web page at work that I want to query data from tables into excel 2007. This web page requires I sign on with a password. I sign in with my normal IE7 browser, then I go to DATA -> connections -> my connections and edit the query. This reads the IE7 cookie cache and I re-POST the data to connect to the server's security by clicking "retry" when it says "the web query returned no data". After I do this, the data imports fine.
I can do this just fine and it only needs to be done once a day. Other users of my application find this difficult which leads to my question:
Is there a way to automatically POST this data back with VB? I'm thinking maybe I should use the cookie property of the IE.Document.cookie?
I'm calling the following login script, before I continue with the web query (set reference to XML library). Look around to find some instructions how you can find your POST parameters.
Sub XMLHttpLogin()
Dim i As Integer
Dim sExpr As String
Dim sPar As String, sURL as String
Dim sResp As String
Dim XMLHttp As MSXML2.XMLHTTP60
Set XMLHttp = New MSXML2.XMLHTTP60
sPar = "name=user1&pass=pass1&form_id=form1" 'The parameters to send.
sURL = "http://www.stackoverflow.com"
With XMLHttp
.Open "POST", sURL, True 'Needs asynchronous connection
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (sPar)
i = 0 'wait until data has been downloaded
Do While i = 0
If .readyState = 4 Then
If .Status = 200 Then Exit Do
End If
DoEvents
Loop
sResp = .responseText 'contains source code of website
sExpr = "not-logged-in" 'look for this string in source code
If InStr(1, sResp, sExpr, vbTextCompare) Then
MsgBox "Not logged in. Error in XMLHttpLogin"
End If
End With
End Sub

Resources