mongolianboss
New Member
- Joined
- Aug 31, 2020
- Messages
- 1
- Office Version
- 2016
- Platform
- Windows
Hello
I have code that uses WinHttp for login. It redirects and needs session key and cookies to authenticate so I can't use QueryTables for authentication.
I also have legacy code that uses QueryTables for pulling data from the same service.
Is it possible to somehow use the same session I'm creating in WinHttp to pull data using QueryTables? At the moment QueryTables won't be authenticated because the session is not shared.
I know can build parser after using WinHttp but it would be much cleaner and I could reuse the legacy code with QueryTables.
My code below:
I have code that uses WinHttp for login. It redirects and needs session key and cookies to authenticate so I can't use QueryTables for authentication.
I also have legacy code that uses QueryTables for pulling data from the same service.
Is it possible to somehow use the same session I'm creating in WinHttp to pull data using QueryTables? At the moment QueryTables won't be authenticated because the session is not shared.
I know can build parser after using WinHttp but it would be much cleaner and I could reuse the legacy code with QueryTables.
My code below:
VBA Code:
Sub Log()
UrlToPostTo = "https://www.test.com"
Set http = New WinHttp.WinHttpRequest
http.Open "GET", UrlToPostTo, False
http.Option(WinHttpRequestOption_EnableRedirects) = True
http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.SetRequestHeader "Connection", "keep-alive"
http.Send
If http.Status = "200" Then
' parse redirect url
response = CStr(http.ResponseText)
searchaction = InStr(1, response, "action", 0) + 8
searchmethod = InStr(1, response, "method", 0) - 2
response = Mid(response, searchaction, searchmethod - searchaction)
response = Replace(response, "amp;", "")
UrlRedirectedTo = response
'create POST request
loginData = "username=user&password=pass"
http.Open "POST", UrlRedirectedTo, False
http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.SetRequestHeader "Connection", "keep-alive"
http.Send loginData
' logged in to www.test.com
End If
With Sheets("Log").QueryTables.Add(Connection:="https://www.test.com/service1/table1", Destination:=Sheets("Log").Range("$A$1"))
.Name = "Log"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Application.DisplayAlerts = False
Application.DisplayAlerts = True
End Sub