• Welcome to Jose's Read Only Forum 2023.
 

WINHTTP Flat API Examples

Started by José Roca, August 29, 2011, 01:27:36 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

José Roca

 
Microsoft Windows HTTP Services (WinHTTP) provides developers with a server-supported, high-level interface to the HTTP/1.1 Internet protocol. WinHTTP is designed to be used primarily in server-based scenarios by server applications that communicate with HTTP servers.

WinINet was designed as an HTTP client platform for interactive desktop applications, such as Microsoft Internet Explorer, Microsoft Office, and Microsoft Money. WinINet displays a user interface for some operations such as collecting user credentials. WinHTTP, however, handles these operations programmatically. Server applications that require HTTP client services should use WinHTTP instead of WinINet. For more information, see Porting WinINet Applications to WinHTTP.

WinHTTP is also designed for use in system services and HTTP-based client applications. However, single-user applications that require FTP protocol functionality, cookie persistence, caching, automatic credential dialog handling, Internet Explorer compatibility, or downlevel platform support should consider using WinINet.

This interface is accessible from C/C++ by using either the WinHTTP application programming interface (API), or by using the IWinHttpRequest and IWinHttpRequestEvents interfaces. WinHTTP is also accessible from script and Microsoft Visual Basic through the WinHTTP object. For more information and descriptions of the individual functions, see the WinHTTP functions reference for the specific language.

Caution  WinHTTP is not reentrant except during asynchronous completion callback. That is, while a thread has a call pending to one of the WinHTTP functions such as WinHttpSendRequest, WinHttpReceiveResponse, WinHttpQueryDataAvailable, WinHttpSendData, or WinHttpWriteData, it must never call WinHTTP a second time until the first call has completed. One scenario under which a second call could occur is as follows: If an application queues an Asynchronous Procedure Call (APC) to the thread that calls into WinHTTP, and if WinHTTP performs an alertable wait internally, the APC can run. If the APC routine happens also to call WinHTTP, it reenters the WinHTTP API, and the internal state of WinHTTP can be corrupted.
WinHTTP 5.1 Features

The following features have been added in version 5.1 of WinHTTP:



  • IPv6 support.

  • AutoProxy capabilities.

  • HTTP/1.0 protocol, including support for keep-alive (persistent) connections and session cookies.

  • HTTP/1.1 chunked transfer support for HTTP responses.

  • Keep-alive pooling of anonymous connections across sessions.

  • Secure Sockets Layer (SSL) functionality, including client certificates. Supported SSL protocols include the following: SSL 2.0, SSL 3.0, and Transport Layer Security (TLS) 1.0.

  • Support for server and proxy authentication, including integrated support for Microsoft Passport 1.4 and the Negotiate/ Kerberos package.

  • Automatic handling of redirects unless suppressed.

  • Scriptable interface in addition to the API.

  • Trace utility to help troubleshoot problems.

A number of WinINet features are not supported in WinHTTP, including URL caching and persistent cookies, autoproxy, autodialing, offline support, and File Transfer Protocol (FTP).

José Roca

 
The following code example includes an If-Modified-Since header in a request. The response header is interpreted to determine whether the target document has been updated.


' ========================================================================================
' The following example shows how to obtain an HINTERNET handle, open an HTTP session,
' create and send a request header, and examine the returned response header.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL dwSize AS DWORD
   LOCAL dwStatusCode AS DWORD
   LOCAL bResults AS LONG
   LOCAL hSession AS DWORD
   LOCAL hConnect AS DWORD
   LOCAL hRequest AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260
   LOCAL wszServerName AS WSTRINGZ * 260
   LOCAL wszVerb AS WSTRINGZ * 260
   LOCAL wszHeaders AS WSTRINGZ * 260

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   ' Specify an HTTP server.
   IF hSession THEN
      wszServerName = "www.microsoft.com" & $NUL
      hConnect = WinHttpConnect(hSession, _
                                wszServerName, _
                                %INTERNET_DEFAULT_HTTP_PORT, _
                                0)
   END IF

   ' Create an HTTP Request handle.
   IF hConnect THEN
      wszVerb = "GET"
      hRequest = WinHttpOpenRequest(hConnect, _
                                    wszVerb, _
                                    "",  _
                                    "", _
                                    BYVAL %WINHTTP_NO_REFERER, _
                                    BYVAL %WINHTTP_DEFAULT_ACCEPT_TYPES, _
                                    0)
   END IF

   ' Add a request header.
   IF hRequest THEN
      wszHeaders = "If-Modified-Since: Mon, 20 Nov 2000 20:00:00 GMT"
      bResults = WinHttpAddRequestHeaders(hRequest, _
                                          wszHeaders, _
                                          -1, _
                                          %WINHTTP_ADDREQ_FLAG_ADD)
   END IF

   ' Send a Request.
   IF bResults THEN
      bResults = WinHttpSendRequest(hRequest, _
                                    BYVAL %WINHTTP_NO_ADDITIONAL_HEADERS, _
                                    0, _
                                    %WINHTTP_NO_REQUEST_DATA, _
                                    0, _
                                    0, _
                                    0)
   END IF

   ' End the request.
   IF bResults THEN
      bResults = WinHttpReceiveResponse(hRequest, %NULL)
   END IF

   ' Use WinHttpQueryHeaders to obtain the header buffer.
   IF bResults THEN
      bResults = WinHttpQueryHeaders(hRequest, _
                                     %WINHTTP_QUERY_STATUS_CODE OR %WINHTTP_QUERY_FLAG_NUMBER, _
                                     "", _
                                     VARPTR(dwStatusCode), _
                                     dwSize, _
                                     %WINHTTP_NO_HEADER_INDEX)
   END IF

   ' Based on the status code, determine whether
   ' the document was recently updated.
   IF bResults THEN
      IF dwStatusCode = 304 THEN
         PRINT "Document has not been updated."
      ELSEIF dwStatusCode = 200 THEN
         PRINT "Document has been updated."
      ELSE
         PRINT "Status code =" dwStatusCode
      END IF
   END IF

   ' Report any errors.
   IF ISFALSE bResults THEN
      PRINT "Error %d has occurred." GetLastError
   END IF

   ' Close open handles.
   IF hRequest THEN WinHttpCloseHandle(hRequest)
   IF hConnect THEN WinHttpCloseHandle(hConnect)
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example shows how to determine whether the current platform is supported.


' ========================================================================================
' The following example shows how to determine whether the current platform is supported.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   IF WinHttpCheckPlatform THEN
      PRINT "This platform is supported by WinHTTP."
   ELSE
      PRINT "This platform is NOT supported by WinHTTP."
   END IF

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example shows you how to retrieve the connection time-out value:


' ========================================================================================
' The following example shows you how to retrieve the connection time-out value.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL hSession AS DWORD
   LOCAL pData AS DWORD
   LOCAL dwSize AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   IF hSession THEN
      ' Use WinHttpQueryOption to retrieve internet options.
      IF WinHttpQueryOption(hSession, _
                            %WINHTTP_OPTION_CONNECT_TIMEOUT, _
                            VARPTR(pdata), _
                            dwSize) THEN
         PRINT "Connection timeout: " pdata
      ELSE
         PRINT "Error " GetLastError " in WinHttpQueryOption"
      END IF
      ' When finished, release the HINTERNET handle.
      WinHttpCloseHandle(hSession)
   ELSE
      PRINT "Error " GetLastError " in in WinHttpOpen."
   END IF

   ' Close open handles.
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example shows how to use secure transaction semantics to download a resource from an HTTPS server. The sample code initializes the Microsoft Windows HTTP Services (WinHTTP) application programming interface (API), selects a target HTTPS server, then opens and sends a request for this secure resource. WinHttpQueryDataAvailable is used with the request handle to determine how much data is available for download, then WinHttpReadData is used to read that data. This process repeats until the entire document has been retrieved and displayed.


' ========================================================================================
' The following example shows how to use secure transaction semantics to download a
' resource from an HTTPS server. The sample code initializes the Microsoft Windows HTTP
' Services (WinHTTP) application programming interface (API), selects a target HTTPS
' server, then opens and sends a request for this secure resource.
' WinHttpQueryDataAvailable is used with the request handle to determine how much data is
' available for download, then WinHttpReadData is used to read that data. This process
' repeats until the entire document has been retrieved and displayed.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL dwSize AS DWORD
   LOCAL dwDownloaded AS DWORD
   LOCAL bResults AS LONG
   LOCAL hSession AS DWORD
   LOCAL hConnect AS DWORD
   LOCAL hRequest AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260
   LOCAL wszServerName AS WSTRINGZ * 260
   LOCAL wszVerb AS WSTRINGZ * 260
   LOCAL strOutBuffer AS STRING

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   ' Specify an HTTP server.
   IF hSession THEN
      wszServerName = "www.microsoft.com"
      hConnect = WinHttpConnect(hSession, _
                                wszServerName, _
                                %INTERNET_DEFAULT_HTTP_PORT, _
                                0)
   END IF


   ' Create an HTTP Request handle.
   IF hConnect THEN
      wszVerb = "GET"
      hRequest = WinHttpOpenRequest(hConnect, _
                                    wszVerb, _
                                    "",  _
                                    "", _
                                    BYVAL %WINHTTP_NO_REFERER, _
                                    BYVAL %WINHTTP_DEFAULT_ACCEPT_TYPES, _
                                    0)
   END IF

   ' Send a Request.
   ' Note: The Microsoft C example uses WINHTTP_FLAG_SECURE for the last
   ' parameter, but I have changed it to 0 because, otherwise, it returns
   ' error 12175 (ERROR_WINHTTP_SECURE_FAILURE)
   IF hRequest THEN
      bResults = WinHttpSendRequest(hRequest, _
                                    BYVAL %WINHTTP_NO_ADDITIONAL_HEADERS, _
                                    0, _
                                    BYVAL %WINHTTP_NO_REQUEST_DATA, _
                                    0, _
                                    0, _
                                    0)
   END IF

   ' End the request.
   IF bResults THEN
      bResults = WinHttpReceiveResponse(hRequest, %NULL)
   END IF

   ' Keep checking for data until there is nothing left.
   IF bResults THEN
      DO
         ' Check for available data.
         dwSize = 0
         IF ISFALSE WinHttpQueryDataAvailable(hRequest, dwSize) THEN
            PRINT "Error " GetLastError " in WinHttpQueryDataAvailable."
            EXIT DO
         ELSE
            ' Allocate space for the buffer.
            strOutBuffer = STRING$(dwSize + 1, $NUL)
            ' Read the data.
            IF ISFALSE WinHttpReadData(hRequest, STRPTR(strOutBuffer), _
                                       dwSize, dwDownloaded) THEN
               PRINT "Error " GetLastError " in WinHttpReadData."
            ELSE
               STDOUT strOutBuffer
            END IF
         END IF
      LOOP WHILE dwSize > 0
   END IF

   ' Report any errors.
   IF ISFALSE bResults THEN
      PRINT "Error " GetLastError " has occurred."
   END IF

   ' Close open handles.
   IF hRequest THEN WinHttpCloseHandle(hRequest)
   IF hConnect THEN WinHttpCloseHandle(hConnect)
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

#5
 
This example shows how to break a URL into its components, update a component, then reconstruct the URL.


' ========================================================================================
' This example shows how to break a URL into its components, update a component, then
' reconstruct the URL.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"
#INCLUDE ONCE "objbase.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL urlComp AS URL_COMPONENTSW
   LOCAL wszUrl1 AS WSTRINGZ * 260
   LOCAL pwszUrl2 AS WSTRINGZ PTR
   LOCAL dwUrlLen AS DWORD
   LOCAL wszExtraInfo AS WSTRINGZ * 260

   wszUrl1 = "http://search.msn.com/results.asp?RS=CHECKED&FORM=MSNH&v=1&q=wininet"

   ' Initialize the URL_COMPONENTS structure.
   urlComp.dwStructSize = SIZEOF(urlComp)

   ' Set required component lengths to non-zero so that they are cracked.
   urlComp.dwSchemeLength    = -1
   urlComp.dwHostNameLength  = -1
   urlComp.dwUrlPathLength   = -1
   urlComp.dwExtraInfoLength = -1

   ' Crack the URL.
   IF ISFALSE WinHttpCrackUrl(wszUrl1, 0, 0, urlComp) THEN
      PRINT "Error " GetLastError " in WinHttpCrackUrl."
   ELSE
      ' Change the search information.
      ' New info is the same length.
      wszExtraInfo = "?RS=CHECKED&FORM=MSNH&v=1&q=winhttp"
      urlComp.lpszExtraInfo = VARPTR(wszExtraInfo)
      ' Obtain the size of the new URL and allocate memory.
      WinHttpCreateUrl(urlComp, 0, "", dwUrlLen)
      pwszUrl2 = CoTaskMemAlloc(dwUrlLen * 2)
      ' Create a new URL.
      IF ISFALSE WinHttpCreateUrl(urlComp, 0, BYVAL pwszUrl2, dwUrlLen * 2) THEN
         PRINT "Error " GetLastError " in WinHttpCreateUrl."
      ELSE
         ' Show both URLs.
         PRINT "Old URL: " wszUrl1
         PRINT "New URL: " @pwszUrl2
      END IF
      CoTaskMemFree pwszUrl2
   END IF

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

#6
 
The following example shows how to decompile, or crack, a URL into its subcomponents, update a component, then reconstruct the URL.


' ========================================================================================
' The following example shows how to decompile, or crack, a URL into its subcomponents,
' update a component, then reconstruct the URL.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"
#INCLUDE ONCE "objbase.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL urlComp AS URL_COMPONENTSW
   LOCAL wszUrl1 AS WSTRINGZ * 260
   LOCAL pwszUrl2 AS WSTRINGZ PTR
   LOCAL dwUrlLen AS DWORD
   LOCAL wszExtraInfo AS WSTRINGZ * 260

   wszUrl1 = "http://search.msn.com/results.asp?RS=CHECKED&FORM=MSNH&v=1&q=wininet"

   ' Initialize the URL_COMPONENTS structure.
   urlComp.dwStructSize = SIZEOF(urlComp)

   ' Set required component lengths to non-zero so that they are cracked.
   urlComp.dwSchemeLength    = -1
   urlComp.dwHostNameLength  = -1
   urlComp.dwUrlPathLength   = -1
   urlComp.dwExtraInfoLength = -1

   ' Crack the URL.
   IF ISFALSE WinHttpCrackUrl(wszUrl1, 0, 0, urlComp) THEN
      PRINT "Error " GetLastError " in WinHttpCrackUrl."
   ELSE
      ' Change the search information.
      ' New info is the same length.
      wszExtraInfo = "?RS=CHECKED&FORM=MSNH&v=1&q=winhttp"
      urlComp.lpszExtraInfo = VARPTR(wszExtraInfo)
      ' Obtain the size of the new URL and allocate memory.
      WinHttpCreateUrl(urlComp, 0, "", dwUrlLen)
      pwszUrl2 = CoTaskMemAlloc(dwUrlLen * 2)
      ' Create a new URL.
      IF ISFALSE WinHttpCreateUrl(urlComp, 0, BYVAL pwszUrl2, dwUrlLen * 2) THEN
         PRINT "Error " GetLastError " in WinHttpCreateUrl."
      ELSE
         ' Show both URLs.
         PRINT "Old URL:  " wszUrl1
         PRINT "New URL:  " @pwszUrl2
      END IF
      CoTaskMemFree pwszUrl2
   END IF

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example code shows how to retrieve the default connection time-out value.


' ========================================================================================
' The following example code shows how to retrieve the default connection time-out value.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL hSession AS DWORD
   LOCAL pData AS DWORD
   LOCAL dwSize AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   IF hSession THEN
      ' Use WinHttpQueryOption to retrieve internet options.
      IF WinHttpQueryOption(hSession, _
                            %WINHTTP_OPTION_CONNECT_TIMEOUT, _
                            VARPTR(pdata), _
                            dwSize) THEN
         PRINT "Connection timeout: " pdata
      ELSE
         PRINT "Error " GetLastError " in WinHttpQueryOption"
      END IF
      ' When finished, release the HINTERNET handle.
      WinHttpCloseHandle(hSession)
   ELSE
      PRINT "Error " GetLastError " in in WinHttpOpen."
   END IF

   ' Close open handles.
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example shows how to use secure transaction semantics to download a resource from an HTTPS server. The sample code initializes the WinHTTP API, selects a target HTTPS server, and then opens and sends a request for this secure resource. WinHttpQueryDataAvailable is used with the request handle to determine how much data is available for download, then WinHttpReadData is used to read that data. This process repeats until the entire document has been retrieved and displayed.


' ========================================================================================
' The following example shows how to use secure transaction semantics to download a resource
' from an HTTPS server. The sample code initializes the WinHTTP API, selects a target HTTPS
' server, and then opens and sends a request for this secure resource.
' WinHttpQueryDataAvailable is used with the request handle to determine how much data is
' available for download, then WinHttpReadData is used to read that data. This process
' repeats until the entire document has been retrieved and displayed.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE "WIN32API.INC"
#INCLUDE "WINHTTP.INC"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL hSession AS DWORD
   LOCAL pData AS DWORD
   LOCAL dwSize AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   IF hSession THEN
      ' Use WinHttpQueryOption to retrieve internet options.
      IF WinHttpQueryOption(hSession, _
                            %WINHTTP_OPTION_CONNECT_TIMEOUT, _
                            VARPTR(pdata), _
                            dwSize) THEN
         PRINT "Connection timeout: " pdata
      ELSE
         PRINT "Error " GetLastError " in WinHttpQueryOption"
      END IF
      ' When finished, release the HINTERNET handle.
      WinHttpCloseHandle(hSession)
   ELSE
      PRINT "Error " GetLastError " in in WinHttpOpen."
   END IF

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example shows how to obtain an HINTERNET handle, open an HTTP session, create and send a request header, and examine the returned response header.


' ========================================================================================
' The following example shows how to obtain an HINTERNET handle, open an HTTP session,
' create and send a request header, and examine the returned response header.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"
#INCLUDE ONCE "objbase.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL dwSize AS DWORD
   LOCAL dwStatusCode AS DWORD
   LOCAL bResults AS LONG
   LOCAL hSession AS DWORD
   LOCAL hConnect AS DWORD
   LOCAL hRequest AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260
   LOCAL wszServerName AS WSTRINGZ * 260
   LOCAL wszVerb AS WSTRINGZ * 260
   LOCAL pwszOutBuffer AS WSTRINGZ PTR

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   ' Specify an HTTP server.
   IF hSession THEN
      wszServerName = "www.microsoft.com"
      hConnect = WinHttpConnect(hSession, _
                                wszServerName, _
                                %INTERNET_DEFAULT_HTTP_PORT, _
                                0)
   END IF

   ' Create an HTTP Request handle.
   IF hConnect THEN
      wszVerb = "GET"
      hRequest = WinHttpOpenRequest(hConnect, _
                                    wszVerb, _
                                    "",  _
                                    "", _
                                    BYVAL %WINHTTP_NO_REFERER, _
                                    BYVAL %WINHTTP_DEFAULT_ACCEPT_TYPES, _
                                    0)
   END IF

   ' Send a Request.
   IF hRequest THEN
      bResults = WinHttpSendRequest(hRequest, _
                                    BYVAL %WINHTTP_NO_ADDITIONAL_HEADERS, _
                                    0, _
                                    %WINHTTP_NO_REQUEST_DATA, _
                                    0, _
                                    0, _
                                    0)
   END IF

   ' End the request.
   IF bResults THEN
      bResults = WinHttpReceiveResponse(hRequest, %NULL)
   END IF

   ' First, use WinHttpQueryHeaders to obtain the size of the buffer.
   IF bResults THEN
      WinHttpQueryHeaders(hRequest, %WINHTTP_QUERY_RAW_HEADERS_CRLF, _
                          BYVAL %WINHTTP_HEADER_NAME_BY_INDEX, %NULL, _
                          dwSize, BYVAL %WINHTTP_NO_HEADER_INDEX)
   END IF

   ' Allocate memory for the buffer.
   IF GetLastError = %ERROR_INSUFFICIENT_BUFFER THEN
      pwszOutBuffer = CoTaskMemAlloc(dwSize)
      ' Now, use WinHttpQueryHeaders to retrieve the header.
      bResults = WinHttpQueryHeaders(hRequest, _
                                      %WINHTTP_QUERY_RAW_HEADERS_CRLF, _
                                      BYVAL %WINHTTP_HEADER_NAME_BY_INDEX, _
                                      pwszOutBuffer, dwSize, _
                                      BYVAL %WINHTTP_NO_HEADER_INDEX)
   END IF

   ' Print the header contents.
   IF bResults THEN
      STDOUT "Header contents: "
      STDOUT @pwszOutBuffer
      CoTaskMemFree pwszOutBuffer
   END IF

   ' Report any errors.
   IF ISFALSE bResults THEN
      PRINT "Error " GetLastError " has occurred."
   END IF

   ' Close open handles.
   IF hRequest THEN WinHttpCloseHandle(hRequest)
   IF hConnect THEN WinHttpCloseHandle(hConnect)
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
This example demonstrates retrieving the connection time-out value:


' ========================================================================================
' This example demonstrates retrieving the connection time-out value.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE "WIN32API.INC"
#INCLUDE "WINHTTP.INC"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL hSession AS DWORD
   LOCAL pData AS DWORD
   LOCAL dwSize AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   IF hSession THEN
      ' Use WinHttpQueryOption to retrieve internet options.
      IF WinHttpQueryOption(hSession, _
                            %WINHTTP_OPTION_CONNECT_TIMEOUT, _
                            VARPTR(pdata), _
                            dwSize) THEN
         PRINT "Connection timeout: " pdata
      ELSE
         PRINT "Error " GetLastError " in WinHttpQueryOption"
      END IF
      ' When finished, release the HINTERNET handle.
      WinHttpCloseHandle(hSession)
   ELSE
      PRINT "Error " GetLastError " in in WinHttpOpen."
   END IF

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
The following example shows how to use secure transaction semantics to download a resource from an Secure Hypertext Transfer Protocol (HTTPS) server. The sample code initializes the WinHTTP application programming interface (API), selects a target HTTPS server, then opens and sends a request for this secure resource. WinHttpQueryDataAvailable is used with the request handle to determine how much data is available for download, then WinHttpReadData is used to read that data. This process repeats until the entire document has been retrieved and displayed.


' ========================================================================================
' The following example shows how to use secure transaction semantics to download a resource
' from an HTTPS server. The sample code initializes the WinHTTP API, selects a target HTTPS
' server, and then opens and sends a request for this secure resource.
' WinHttpQueryDataAvailable is used with the request handle to determine how much data is
' available for download, then WinHttpReadData is used to read that data. This process
' repeats until the entire document has been retrieved and displayed.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE "WIN32API.INC"
#INCLUDE "WINHTTP.INC"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL dwSize AS DWORD
   LOCAL dwDownloaded AS DWORD
   LOCAL bResults AS LONG
   LOCAL hSession AS DWORD
   LOCAL hConnect AS DWORD
   LOCAL hRequest AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260
   LOCAL wszServerName AS WSTRINGZ * 260
   LOCAL wszVerb AS WSTRINGZ * 260
   LOCAL strOutBuffer AS STRING

   dwSize = 4  ' size of a DWORD

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent ="A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   ' Specify an HTTP server.
   IF hSession THEN
      wszServerName = "www.microsoft.com"
      hConnect = WinHttpConnect(hSession, _
                                wszServerName, _
                                %INTERNET_DEFAULT_HTTP_PORT, _
                                0)
   END IF


   ' Create an HTTP Request handle.
   IF hConnect THEN
      wszVerb = "GET"
      hRequest = WinHttpOpenRequest(hConnect, _
                                    wszVerb, _
                                    BYVAL %NULL,  _
                                    BYVAL %NULL, _
                                    BYVAL %WINHTTP_NO_REFERER, _
                                    BYVAL %WINHTTP_DEFAULT_ACCEPT_TYPES, _
                                    0)
   END IF

   ' Send a Request.
   ' Note: The Microsoft C example uses WINHTTP_FLAG_SECURE for the last
   ' parameter, but I have changed it to 0 because, otherwise, it returns
   ' error 12175 (ERROR_WINHTTP_SECURE_FAILURE)
   IF hRequest THEN
      bResults = WinHttpSendRequest(hRequest, _
                                    BYVAL %WINHTTP_NO_ADDITIONAL_HEADERS, _
                                    0, _
                                    %WINHTTP_NO_REQUEST_DATA, _
                                    0, _
                                    0, _
                                    0)
   END IF

   ' End the request.
   IF bResults THEN
      bResults = WinHttpReceiveResponse(hRequest, %NULL)
   END IF

   ' Keep checking for data until there is nothing left.
   IF bResults THEN
      DO
         ' Check for available data.
         dwSize = 0
         IF ISFALSE WinHttpQueryDataAvailable(hRequest, dwSize) THEN
            PRINT "Error " GetLastError " in WinHttpQueryDataAvailable."
            EXIT DO
         ELSE
            ' Allocate space for the buffer.
            strOutBuffer = STRING$(dwSize + 1, $NUL)
            ' Read the data.
            IF ISFALSE WinHttpReadData(hRequest, BYVAL STRPTR(strOutBuffer), _
                                       dwSize, dwDownloaded) THEN
               PRINT "Error " GetLastError " in WinHttpReadData."
            ELSE
               STDOUT strOutBuffer
            END IF
         END IF
      LOOP WHILE dwSize > 0
   END IF

   ' Report any errors.
   IF ISFALSE bResults THEN
      PRINT "Error " GetLastError " has occurred."
   END IF

   ' Close open handles.
   IF hRequest THEN WinHttpCloseHandle(hRequest)
   IF hConnect THEN WinHttpCloseHandle(hConnect)
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
This example shows how to set new time-out values using WinHttpSetTimeouts.


' ========================================================================================
' The following example shows you how to retrieve the connection time-out value.
' ========================================================================================

' CSED_PBCC - Use the console compiler
#COMPILE EXE
#DIM ALL
#INCLUDE ONCE "windows.inc"
#INCLUDE ONCE "winhttp.inc"

' ========================================================================================
' Main
' ========================================================================================
FUNCTION PBMAIN () AS LONG

   LOCAL hSession AS DWORD
   LOCAL wszUserAgent AS WSTRINGZ * 260

   ' Use WinHttpOpen to obtain a session handle.
   wszUserAgent = "A WinHTTP Example Program/1.0"
   hSession = WinHttpOpen(wszUserAgent, _
                          %WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _
                          BYVAL %WINHTTP_NO_PROXY_NAME, _
                          BYVAL %WINHTTP_NO_PROXY_BYPASS, _
                          0)

   IF hSession THEN
      ' Use WinHttpSetTimeouts to set a new time-out values.
      IF ISFALSE WinHttpSetTimeouts(hSession, 10000, 10000, 10000, 10000) THEN
         PRINT "Error " GetLastError " in WinHttpSetTimeouts."
      ELSE
         PRINT "Timeouts set"
      END IF

      ' PLACE ADDITIONAL CODE HERE.

      ' When finished, release the HINTERNET handle.
      WinHttpCloseHandle(hSession)
   ELSE
      PRINT "Error " GetLastError " in in WinHttpOpen."
   END IF

   ' Close open handles.
   IF hSession THEN WinHttpCloseHandle(hSession)

   WAITKEY$

END FUNCTION
' ========================================================================================


José Roca

 
This example shows how to convert an HTTP formatted date to a SYSTEMTIME structure.


DIM ST AS SYSTEMTIME
DIM wszTimeStr AS WSTRINGZ * 260
DIM nError AS LONG

' Convert the HTTP string to a SYSTEMTIME structure.
wszTimeStr = "Tue, 21 Nov 2000 01:06:53 GMT"
IF WinHttpTimeToSystemTime(wszTimeStr, ST) = 0 THEN
    nError = GetLastError
    PRINT "Error " nError " in WinHttpTimeToSystemTime."
ELSE
    ' Print the date.
    PRINT "The U.S. formatted date is " & _
          ST.wMonth & "/" & ST.wDay & "/" & ST.wYear
END IF