I have been trying to get some status information from a http request I made using Wininet in VBA and no matter what flags I use it does not seem to work.
First I tried to get the status code, and after declaring the variables and obtaining a valid handle from httpOpenRequest I always get a zero status code when calling HttpQueryInfo.
Here is my code, the URL was cracked into server/path/port.
The server needs password authentication.
Declare Function HttpQueryInfo Lib "wininet.dll" Alias "HttpQueryInfoA" (ByVal hHttpRequest As Long, _
ByVal lInfoLevel As Long, _
ByRef sBuffer As Any, _
ByRef lBufferLength As Long, _
ByRef lIndex As Long) As Boolean
Const ERROR_INSUFFICIENT_BUFFER = 122
Const HTTP_QUERY_RAW_HEADERS_CRLF = 22
Const HTTP_QUERY_STATUS_CODE = 19
Const HTTP_QUERY_FLAG_NUMBER = &H20000000
Const STR_APP_NAME As String = "Uploader"
Dim hOpen As Long
Dim hConnection As Long
Dim hOpenRequest As Long
Dim dwStatusLng As Long
Dim dwStatusStr As String
Dim dwStatusSize As Long
hOpen = InternetOpen(STR_APP_NAME, INTERNET_OPEN_TYPE_PRECONFIG, vbNullString, vbNullString, 0) 'returns handle<>0 and Err.LastDllError=0
hConnection = InternetConnect(hOpen, sHttpServer, lHttpPort, username, password, INTERNET_SERVICE_HTTP, 0, 0) 'returns handle<>0 and Err.LastDllError=0
hOpenRequest = HttpOpenRequest(hConnection, "POST", sUploadPage, "HTTP/1.0", vbNullString, 0, INTERNET_FLAG_RELOAD, 0) 'returns handle<>0 and Err.LastDllError=0
dwStatusSize = Len(dwStatusLng)
HttpQueryInfo(hOpenRequest, HTTP_QUERY_FLAG_NUMBER Or HTTP_QUERY_STATUS_CODE, dwStatusLng, dwStatusSize, 0)
Since the buffer is declared byRef, if I do not enforce byVal in the call, then the function fails but no error is raised: Err.LastDllError=122, dwStatusLng=0, dwStatusSize=4
If I pass the buffer byVal (as was suggested on some website) then the function fails with error 122 ERROR_INSUFFICIENT_BUFFER.
How do I resize a variable of type Long? This is to me mindblowing.
How do I get a valid status code (as a number) from this function in VB?
On the other hand, if I try to retrieve the headers, then the buffer seems to be too small even though I declared it as string.
dwStatusSize = Len(dwStatusStr)
If Not (HttpQueryInfo(hOpenRequest, HTTP_QUERY_RAW_HEADERS_CRLF, dwStatusStr, dwStatusSize, 0)) Then
If Err.LastDllError = ERROR_INSUFFICIENT_BUFFER Then
dwStatusStr = String(dwStatusSize, 0)
First time always fails so I resize the buffer.
if I call the function again with the resized buffer, excel will crash (similar to the situation of declaring Dim dwStatusStr As String * 1024, in which case it will crash at first call)
Bottom line: if the buffer and bufferLenght are declared byRef, then:
if buffer is of type Long, why does the size not suffice?
if the buffer is of type string, why resizing causes excel to crash?
Any help would be much appreciated.