WinHttp

  • Copyright © 2013-2016 Dragana R.


WinHttp Function Notes

WinHttp

Welcome to the helpfile of WinHttp!

WinHttp-UDFs for AutoIt and this helpfile are created by trancexx and ProgAndy. Current version is 1.6.4.1

About WinHTTP (MSDN)

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.

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

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, File Transfer Protocol (FTP), and the Gopher protocol.

For more information about changes introduced in version 5.1, see What's New in WinHTTP 5.1.


Function Reference

_WinHttpAddRequestHeaders

Adds one or more HTTP request headers to the HTTP request handle.

Syntax

#include "WinHttp.au3"
_WinHttpAddRequestHeaders ($hRequest, $sHeaders [, $iModifiers = Default ])

Parameters

$hRequest | Handle returned by _WinHttpOpenRequest function.
$sHeader | [optional] Header(s) to append to the request.
$iModifier | [optional] Contains the flags used to modify the semantics of this function. Default is $WINHTTP_ADDREQ_FLAG_ADD_IF_NEW.

Return Value

Success - Returns 1
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

In case of multiple additions at once use @CRLF to separate each $hRequest and responded $sHeaders and $iModifiers.

Related

_WinHttpOpenRequest, _WinHttpQueryHeaders

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; !!!Note that this example will fail because of invalid username and password!!!

Global $sAddress = "secure.imdb.com"
Global $sUserName = "SomeUserName"
Global $sPassword = "SomePassword"
; Post data:
Global $sPostData = "login=" & $sUserName & "&password=" & $sPassword & "&u=https%3A%2F%2Fsecure.imdb.com%2Fregister-imdb%2Flogin"

; Initialize and get session handle
Global $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5")

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sAddress, $INTERNET_DEFAULT_HTTPS_PORT)

; Make a request
Global $hRequest = _WinHttpOpenRequest($hConnect, _
"POST", _
"register-imdb/login", _
Default, _
Default, _
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", _
$WINHTTP_FLAG_SECURE)

; Add header fields to the request
_WinHttpAddRequestHeaders($hRequest, "Accept-Language: en-us,en;q=0.5")
_WinHttpAddRequestHeaders($hRequest, "Content-Type: application/x-www-form-urlencoded")
_WinHttpAddRequestHeaders($hRequest, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
_WinHttpAddRequestHeaders($hRequest, "Keep-Alive: 300")
_WinHttpAddRequestHeaders($hRequest, "Connection: keep-alive")

; Send it
_WinHttpSendRequest($hRequest, -1, $sPostData)
; Wait for the response
_WinHttpReceiveResponse($hRequest)
; Check if there is a response
Global $sHeader, $sReturned
If _WinHttpQueryDataAvailable($hRequest) Then
$sHeader = _WinHttpQueryHeaders($hRequest)
MsgBox(64, "Header", $sHeader)
Do
$sReturned &= _WinHttpReadData($hRequest)
Until @error
; Print returned
ConsoleWrite($sReturned)
Else
ConsoleWriteError("!No data available." & @CRLF)
MsgBox(48, "Failure", "No data available.")
EndIf

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpCheckPlatform

Determines whether the current platform is supported by this version of Microsoft Windows HTTP Services (WinHTTP).

Syntax

#include "WinHttp.au3"
_WinHttpCheckPlatform()

Parameters

None.

Return Value

Success - Returns 1 if current platform is supported
- Returns 0 if current platform is not supported
Failure - Returns 0 and sets @error:
1 - DllCall failed

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

If Not _WinHttpCheckPlatform() Then
MsgBox(48, "Caution", "WinHTTP not available on your system!")
Exit 1
EndIf

;... The rest of the code


Function Reference

_WinHttpCloseHandle

Closes a single handle.

Syntax

#include "WinHttp.au3"
_WinHttpCloseHandle($hInternet)

Parameters

$hInternet Valid handle to be closed.

Return Value

Success - Returns 1
Failure - Returns 0 and sets @error:
1 - DllCall failed

Related

_WinHttpConnect, _WinHttpOpen, _WinHttpOpenRequest

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
If @error Then
MsgBox(48, "Error", "Error initializing the usage of WinHTTP functions.")
Exit 1
EndIf

; Close it
_WinHttpCloseHandle($hOpen)
If @error Then
ConsoleWriteError("!Error closing the handle. @error = " & @error & @CRLF)
MsgBox(48, "Error", "Error closing the handle." & @CRLF & "Error number is " & @error)
Else
ConsoleWrite("+ Handle is succesfully closed." & @CRLF)
MsgBox(64, "Closed", "Handle is succesfully closed.")
EndIf


Function Reference

_WinHttpConnect

Specifies the initial target server of an HTTP request and returns connection handle to an HTTP session for that initial target.

Syntax

#include "WinHttp.au3"
_WinHttpConnect($hSession, $sServerName [, $iServerPort = Default ])

Parameters

$hSession | Valid WinHttp session handle returned by a previous call to _WinHttpOpen().
$sServerName | Host name of an HTTP server. In case URI scheme (http://, https://, ...) is specified $iServerPort is ignored.
$iServerPort | [optional] TCP/IP port on the server to which a connection is made (default is $INTERNET_DEFAULT_PORT)

Return Value

Success - Returns a valid connection handle to the HTTP session
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

$iServerPort can be defined via global constants $INTERNET_DEFAULT_PORT, $INTERNET_DEFAULT_HTTP_PORT or $INTERNET_DEFAULT_HTTPS_PORT

Related

_WinHttpOpen

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "http://www.pravda.ru")
If @error Then
MsgBox(48, "Error", "Error getting connection handle." & @CRLF & "Error number is " & @error)
Else
ConsoleWrite("+ Connection handle $hConnect = " & $hConnect & @CRLF)
MsgBox(64, "Yes!", "Handle is get! $hConnect = " & $hConnect)
EndIf

; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpCrackUrl

Separates a URL into its component parts such as host name and path.

Syntax

#include "WinHttp.au3"
_WinHttpCrackUrl($sURL [, $iFlag = Default ])

Parameters

$sURL | String. Canonical URL to separate.
$iFlag | [optional] Flag that control the operation. Default is $ICU_ESCAPE

Return Value

Success - Returns array with 8 elements:
$array[0] - scheme name
$array[1] - internet protocol scheme
$array[2] - host name
$array[3] - port number
$array[4] - user name
$array[5] - password
$array[6] - URL path
$array[7] - extra information
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

$iFlag is defined in WinHttpConstants.au3 and can be:
$ICU_DECODE - Converts characters that are "escape encoded" (%xx) to their non-escaped form.
$ICU_ESCAPE - Escapes certain characters to their escape sequences (%xx).

Related

_WinHttpCreateUrl

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"
#include <Array.au3>

Opt("MustDeclareVars", 1)

; Cracking URL
Global $aUrl = _WinHttpCrackUrl("http://www.autoitscript.com/forum/index.php?showforum=9")
_ArrayDisplay($aUrl, "_WinHttpCrackUrl()")


Function Reference

_WinHttpCreateUrl

Creates a URL from array of components such as the host name and path.

Syntax

#include "WinHttp.au3"
_WinHttpCreateUrl($aURLArray)

Parameters

$aURLArray Array of URL data.

Return Value

Success - Returns created URL
Failure - Returns empty string and sets @error:
1 - Invalid input.
2 - Initial DllCall failed
3 - Main DllCall failed

Remarks

Input is one dimensional 8 elements in size array:
- first element [0] scheme name
- second element [1] internet protocol scheme
- third element [2] host name
- fourth element [3] port number
- fifth element [4] user name
- sixth element [5] password
- seventh element [6] URL path
- eighth element [7] extra information

Related

_WinHttpCrackUrl

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Creating URL out of array of components:
Global $aURL[8] = ["http", 1, "www.autoitscript.com", 80, "Jon", "deadPiXels", "admin.php"]
MsgBox(0, "Created URL", _WinHttpCreateUrl($aURL))


Function Reference

_WinHttpDetectAutoProxyConfigUrl

Finds the URL for the Proxy Auto-Configuration (PAC) file.

Syntax

#include "WinHttp.au3"
_WinHttpDetectAutoProxyConfigUrl($iAutoDetectFlags)

Parameters

$iAutoDetectFlags Specifies what protocols to use to locate the PAC file.

Return Value

Success - Returns URL for the PAC file.
Failure - Returns empty string and sets @error:
1 - DllCall failed
2 - Internal failure.

Remarks

$iAutoDetectFlags values are defined in WinHttpconstants.au3

Related

_WinHttpGetDefaultProxyConfiguration, _WinHttpGetIEProxyConfigForCurrentUser, _WinHttpSetDefaultProxyConfiguration

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; This could take some time
Global $sPACurl = _WinHttpDetectAutoProxyConfigUrl(BitOR($WINHTTP_AUTO_DETECT_TYPE_DHCP, $WINHTTP_AUTO_DETECT_TYPE_DNS_A))

MsgBox(64, "_WinHttpDetectAutoProxyConfigUrl", "The URL for the Proxy Auto-Configuration (PAC) file is: " & $sPACurl)


Function Reference

_WinHttpGetDefaultProxyConfiguration

Retrieves the default WinHttp proxy configuration.

Syntax

#include "WinHttp.au3"
_WinHttpGetDefaultProxyConfiguration()

Parameters

None.

Return Value

Success - Returns array with 3 elements:
$array[0] - Integer. Access type.
$array[1] - String. Proxy server list.
$array[2] - String. Proxy bypass list.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

Access types are defined in WinHttpconstants.au3:
$WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0
$WINHTTP_ACCESS_TYPE_NO_PROXY = 1
$WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3

Related

_WinHttpDetectAutoProxyConfigUrl, _WinHttpGetIEProxyConfigForCurrentUser, _WinHttpSetDefaultProxyConfiguration

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"
#include <Array.au3>

Opt("MustDeclareVars", 1)

; Current WinHTTP proxy configuration:
Global $aProxy = _WinHttpGetDefaultProxyConfiguration()
_ArrayDisplay($aProxy, "Current WinHTTP proxy configuration")


Function Reference

_WinHttpGetIEProxyConfigForCurrentUser

Retrieves the Internet Explorer proxy configuration for the current user.

Syntax

#include "WinHttp.au3"
_WinHttpGetIEProxyConfigForCurrentUser()

Parameters

None.

Return Value

Success - Returns array with 4 elements:
$array[0] - if 1 indicates that the IE proxy configuration for the current user specifies "automatically detect settings",
$array[1] - auto-configuration URL if the IE proxy configuration for the current user specifies "Use automatic proxy configuration",
$array[2] - proxy URL if the IE proxy configuration for the current user specifies "use a proxy server",
$array[3] - optional proxy by-pass server list.
Failure - Returns 0 and sets @error:
1 - DllCall failed
2 - Internal failure.

Related

_WinHttpDetectAutoProxyConfigUrl, _WinHttpGetDefaultProxyConfiguration, _WinHttpSetDefaultProxyConfiguration

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"
#include <Array.au3>

Opt("MustDeclareVars", 1)

; Internet Explorer proxy configuration for the current user:
Global $aIEproxy = _WinHttpGetIEProxyConfigForCurrentUser()
_ArrayDisplay($aIEproxy, "Internet Explorer proxy configuration")


Function Reference

_WinHttpOpen

Initializes the use of WinHttp functions and returns a WinHttp-session handle.

Syntax

#include "WinHttp.au3"
_WinHttpOpen([$sUserAgent = Default [, $iAccessType = Default [, $sProxyName = Default [, $sProxyBypass = Default [, $iFlag = Default ]]]]])

Parameters

$sUserAgent | [optional] The name of the application or entity calling the WinHttp functions.
$iAccessType | [optional] Type of access required. Default is $WINHTTP_ACCESS_TYPE_NO_PROXY.
$sProxyName | [optional] The name of the proxy server to use when proxy access is specified by setting $iAccessType to $WINHTTP_ACCESS_TYPE_NAMED_PROXY. Default is $WINHTTP_NO_PROXY_NAME.
$sProxyBypass | [optional] An optional list of host names or IP addresses, or both, that should not be routed through the proxy when $iAccessType is set to $WINHTTP_ACCESS_TYPE_NAMED_PROXY. Default is $WINHTTP_NO_PROXY_BYPASS.
$iFlag | [optional] Integer containing the flags that indicate various options affecting the behavior of this function. Default is 0.

Return Value

Success - Returns valid session handle.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

You are strongly discouraged to use WinHTTP in asynchronous mode with AutoIt. AutoIt's callback implementation can't handle reentrancy properly.
For asynchronous mode set $iFlag to $WINHTTP_FLAG_ASYNC. In that case $WINHTTP_OPTION_CONTEXT_VALUE for the handle will inernally be set to $WINHTTP_FLAG_ASYNC also.

Related

_WinHttpCloseHandle, _WinHttpConnect

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
If @error Then
MsgBox(48, "Error", "Error initializing the usage of WinHTTP functions.")
Exit 1
EndIf

; Close it
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpOpenRequest

Creates an HTTP request handle.

Syntax

#include "WinHttp.au3"
_WinHttpOpenRequest($hConnect [, $sVerb = Default [, $sObjectName = Default [, $sVersion = Default [, $sReferrer = Default [, $sAcceptTypes = Default [, $iFlags = Default ]]]]]])

Parameters

$hConnect | Handle to an HTTP session returned by _WinHttpConnect().
$sVerb | [optional] HTTP verb to use in the request. Default is "GET".
$sObjectName | [optional] The name of the target resource of the specified HTTP verb.
$sVersion | [optional] HTTP version. Default is "HTTP/1.1"
$sReferrer | [optional] URL of the document from which the URL in the request $sObjectName was obtained. Default is $WINHTTP_NO_REFERER.
$sAcceptTypes | [optional] Media types accepted by the client. Default is $WINHTTP_DEFAULT_ACCEPT_TYPES
$iFlags | [optional] Integer specifying the Internet flag values. Default is $WINHTTP_FLAG_ESCAPE_DISABLE

Return Value

Success - Returns valid session handle.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Related

_WinHttpCloseHandle, _WinHttpConnect, _WinHttpSendRequest

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; !!!Note that this example will fail because of invalid username and password!!!

; Authentication data
Global $sUsername = "UserName"
Global $sPassword = "Password"

; Address
Global $sAddress = "space.livevn.com"

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sAddress)

; Request
Global $hRequest = _WinHttpOpenRequest($hConnect, _
"POST", _ ; verb
"/do.php?ac=71ee30ae117cddace55bd01714904227&&ref", _ ; target
Default, _ ; version
"http://space.livevn.com/index.php", _ ; referer
"*/*") ; accept

; Send it
_WinHttpSendRequest($hRequest, _
"Content-Type: application/x-www-form-urlencoded" & @CRLF, _
"username=" & $sUsername & "&password=" & $sPassword & "&loginsubmit=&loginsubmit=loginnnnnnnnnnn&refer=network.html&formhash=c51a94db")

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; See what's returned
If _WinHttpQueryDataAvailable($hRequest) Then
Global $sHeader = _WinHttpQueryHeaders($hRequest)
ConsoleWrite($sHeader & @CRLF)
; Check if proper cookie is given
If StringInStr($sHeader, 'Set-Cookie: uchome_loginuser=' & $sUsername) Then
MsgBox(0, "", "Login success")
Else
MsgBox(0, "", "Login failed")
EndIf
Else
MsgBox(48, "Error", "Site is experiencing problems.")
EndIf

; Close open handles and exit
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpQueryAuthSchemes

Returns the authorization schemes that are supported by the server.

Syntax

#include "WinHttp.au3"
_WinHttpQueryAuthSchemes($hRequest, Byref $iSupportedSchemes, Byref $iFirstScheme, Byref $iAuthTarget)

Parameters

$hRequest | Valid handle returned by _WinHttpSendRequest().
$iSupportedSchemes | [out] Supported authentication schemes. See remarks.
$iFirstScheme | [out] First authentication scheme listed by the server. See remarks.
$iAuthTarget | [out] A flag that contains the authentication target. See remarks.

Return Value

Success - Returns 1
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

_WinHttpQueryAuthSchemes() is called after _WinHttpQueryHeaders().
Arguments are accepted ByRef.
Both $iSupportedSchemes and $iFirstScheme is set to combination of any of $WINHTTP_AUTH_SCHEME_ flags.
$iAuthTarget parameter is set to one or more $WINHTTP_AUTH_TARGET_ constants values.

Related

_WinHttpSetCredentials, _WinHttpQueryHeaders, _WinHttpOpenRequest

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

Global Const $sAddress = "192.168.1.1" ; some address that requires authorization

; Credentials (incorrect values here - the example will fail therefore!)
Global Const $sUserName = "user", $sPassword = "password"

; Login and print the result to the console
ConsoleWrite(_LoginExample($sAddress, $sUserName, $sPassword) & @CRLF)

; The function
Func _LoginExample($sAddress, $sUserName, $sPassword)
Local $sOut ; this variable data will be returned

; Initialize and get session handle
Local $hOpen = _WinHttpOpen()
If $hOpen Then
; Get connection handle
Local $hConnect = _WinHttpConnect($hOpen, $sAddress)
If $hConnect Then
; Specify the reguest
Local $hRequest = _WinHttpOpenRequest($hConnect)
If $hRequest Then
; Send the request
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; Query status code
Local $iStatusCode = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_STATUS_CODE)
; Check status code
If $iStatusCode = $HTTP_STATUS_DENIED Or $iStatusCode = $HTTP_STATUS_PROXY_AUTH_REQ Then
; Query Authorization scheme
Local $iSupportedSchemes, $iFirstScheme, $iAuthTarget
If _WinHttpQueryAuthSchemes($hRequest, $iSupportedSchemes, $iFirstScheme, $iAuthTarget) Then
; Set passed credentials
_WinHttpSetCredentials($hRequest, $iAuthTarget, $iFirstScheme, $sUserName, $sPassword)
; Send request again now
_WinHttpSendRequest($hRequest)
; And wait for the response again
_WinHttpReceiveResponse($hRequest)
EndIf
EndIf

; Check if there is any data available and read if yes
Local $sChunk
If _WinHttpQueryDataAvailable($hRequest) Then
While 1
$sChunk = _WinHttpReadData($hRequest)
If @error Then ExitLoop
$sOut &= $sChunk
WEnd
EndIf

; Close handles when they are not needed any more
_WinHttpCloseHandle($hRequest)
EndIf
_WinHttpCloseHandle($hConnect)
EndIf
_WinHttpCloseHandle($hOpen)
EndIf

; Return whatever is read
Return $sOut
EndFunc


Function Reference

_WinHttpQueryDataAvailable

Returns the availability to be read with _WinHttpReadData().

Syntax

#include "WinHttp.au3"
_WinHttpQueryDataAvailable($hRequest)

Parameters

$hRequest handle returned by _WinHttpOpenRequest().

Return Value

Success - Returns 1 if data is available.
- Returns 0 if no data is available.
- @extended receives the number of available bytes.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

_WinHttpReceiveResponse must have been called for this handle and completed before _WinHttpQueryDataAvailable is called.

Related

_WinHttpOpenRequest, _WinHttpReadData, _WinHttpReceiveResponse

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "google.com")
; Specify the reguest
Global $hRequest = _WinHttpOpenRequest($hConnect)
; Send request
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; Check there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then
MsgBox(64, "OK", "Data from google.com is available!")
Else
MsgBox(48, "Error", "Site is experiencing problems (or you).")
EndIf

; Clean
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpQueryHeaders

Retrieves header information associated with an HTTP request.

Syntax

#include "WinHttp.au3"
_WinHttpQueryHeaders($hRequest [, $iInfoLevel = Default [, $sName = Default [, $iIndex = Default ]]])

Parameters

$hRequest | Handle returned by _WinHttpOpenRequest().
$iInfoLevel | [optional] A combination of attribute and modifier flags. Default is $WINHTTP_QUERY_RAW_HEADERS_CRLF.
$sName | [optional] Header name string. Default is $WINHTTP_HEADER_NAME_BY_INDEX.
$iIndex | [optional] Index used to enumerate multiple headers with the same name

Return Value

Success - Returns string that contains header.
- @extended is set to the index of the next header
Failure - Returns empty string and sets @error:
1 - DllCall failed

Related

_WinHttpAddRequestHeaders, _WinHttpOpenRequest

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Open needed handles
Global $hOpen = _WinHttpOpen()
Global $hConnect = _WinHttpConnect($hOpen, "msdn.microsoft.com")
; Specify the reguest:
Global $hRequest = _WinHttpOpenRequest($hConnect, Default, "en-us/library/aa384101(VS.85).aspx")

; Send request
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; Get full header
Global $sHeader = _WinHttpQueryHeaders($hRequest)

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; Display retrieved header
MsgBox(0, "Header", $sHeader)


Function Reference

_WinHttpQueryOption

Queries an Internet option on the specified handle.

Syntax

#include "WinHttp.au3"
_WinHttpQueryOption($hInternet, $iOption)

Parameters

$hInternet | Handle on which to query information.
$iOption | Internet option to query.

Return Value

Success - Returns data containing requested information.
Failure - Returns empty string and sets @error:
1 - Initial DllCall failed
2 - Main DllCall failed

Remarks

Type of the returned data varies on request.

Related

_WinHttpSetOption

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()

; Set User-Agent string
_WinHttpSetOption($hOpen, $WINHTTP_OPTION_USER_AGENT, "Who the fuc*k is Alice???")

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "google.com")

; Specify the reguest
Global $hRequest = _WinHttpOpenRequest($hConnect)

; Send request
_WinHttpSendRequest($hRequest)

; Check what User-Agent string was used
ConsoleWrite("! Custom agent: " & _WinHttpQueryOption($hOpen, $WINHTTP_OPTION_USER_AGENT) & @CRLF & @CRLF)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

Global $sHeader
; If there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header

; Clean
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; Display retrieved header
ConsoleWrite($sHeader & @CRLF)


Function Reference

_WinHttpReadData

Reads data from a handle opened by the _WinHttpOpenRequest() function.

Syntax

#include "WinHttp.au3"
_WinHttpReadData($hRequest [, $iMode = Default [, $iNumberOfBytesToRead = Default ]])

Parameters

$hRequest | Valid handle returned from a previous call to _WinHttpOpenRequest().
$iMode | [optional] Integer representing reading mode. Default is 0 (charset is decoded as it is ANSI).
$iNumberOfBytesToRead | [optional] The number of bytes to read. Default is 8192 bytes.

Return Value

Success - Returns data read.
- @extended receives the number of bytes read.

Remarks

$iMode can have these values:
0 - ANSI
1 - UTF8
2 - Binary

Related

_WinHttpOpenRequest, _WinHttpWriteData

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize
Global $hOpen = _WinHttpOpen()

If @error Then
MsgBox(48, "Error", "Error initializing the usage of WinHTTP functions.")
Exit 1
EndIf

; Specify what to connect to
Global $hConnect = _WinHttpConnect($hOpen, "yahoo.com") ; <- yours here
If @error Then
MsgBox(48, "Error", "Error specifying the initial target server of an HTTP request.")
_WinHttpCloseHandle($hOpen)
Exit 2
EndIf

; Create request
Global $hRequest = _WinHttpOpenRequest($hConnect)
If @error Then
MsgBox(48, "Error", "Error creating an HTTP request handle.")
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)
Exit 3
EndIf

; Send it
_WinHttpSendRequest($hRequest)
If @error Then
MsgBox(48, "Error", "Error sending specified request.")
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)
Exit 4
EndIf

; Wait for the response
_WinHttpReceiveResponse($hRequest)
If @error Then
MsgBox(48, "Error", "Error waiting for the response from the server.")
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)
Exit 5
EndIf

; See if there is data to read
Global $sChunk, $sData
If _WinHttpQueryDataAvailable($hRequest) Then
; Read
While 1
$sChunk = _WinHttpReadData($hRequest)
If @error Then ExitLoop
$sData &= $sChunk
WEnd
ConsoleWrite($sData & @CRLF) ; print to console
Else
MsgBox(48, "Error", "Site is experiencing problems.")
EndIf

; Close handles when they are not needed any more
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpReceiveResponse

Waits to receive the response to an HTTP request initiated by WinHttpSendRequest().

Syntax

#include "WinHttp.au3"
_WinHttpReceiveResponse($hRequest)

Parameters

$hRequest Handle returned by _WinHttpOpenRequest() and sent by _WinHttpSendRequest().

Return Value

Success - Returns 1.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

Call to _WinHttpReceiveResponse() must be done before _WinHttpQueryDataAvailable() and _WinHttpReadData().

Related

_WinHttpOpenRequest, _WinHttpSetTimeouts

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize
Global $hOpen = _WinHttpOpen()
; Specify what to connect to
Global $hConnect = _WinHttpConnect($hOpen, "en.wikipedia.org")
; Create request
Global $hRequest = _WinHttpOpenRequest($hConnect, -1, "wiki/Manchester_United_F.C.")
; Send it
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)
If @error Then
MsgBox(48, "Error", "Error ocurred for WinHttpReceiveResponse, Error number is " & @error)
Else
MsgBox(64, "All right!", "Server at 'en.wikipedia.org' processed the request.")
EndIf

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpSendRequest

Sends the specified request to the HTTP server.

Syntax

#include "WinHttp.au3"
_WinHttpSendRequest($hRequest [, $sHeaders = Default [, $sOptional = Default [, $iTotalLength = Default [, $iContext = Default ]]]])

Parameters

$hRequest | Handle returned by _WinHttpOpenRequest().
$sHeaders | [optional] Additional headers to append to the request. Default is $WINHTTP_NO_ADDITIONAL_HEADERS.
$vOptional | [optional] Optional data to send immediately after the request headers. Default is $WINHTTP_NO_REQUEST_DATA.
$iTotalLength | [optional] Length, in bytes, of the total optional data sent. Default is 0.
$iContext | [optional] Application-defined value that is passed, with the request handle, to any callback functions. Default is 0.

Return Value

Success - Returns 1.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

Specifying optional data $vOptional will cause $iTotalLength to receive the size of that data if left default value.

Related

_WinHttpOpenRequest

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

; http://www.w3schools.com/php/demo_form_validation_escapechar.php

$sUserName = "SomeUserName"
$sEmail = "some.email@something.com"

$sDomain = "www.w3schools.com"
$sPage = "/php/demo_form_validation_escapechar.php"

; Data to send
$sAdditionalData = "name=" & $sUserName & "&email=" & $sEmail

; Initialize and get session handle
$hOpen = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0")

; Get connection handle
$hConnect = _WinHttpConnect($hOpen, $sDomain)

; Make a request
$hRequest = _WinHttpOpenRequest($hConnect, "POST", $sPage)

; Send it. Specify additional data to send too. This is required by the Google API:
_WinHttpSendRequest($hRequest, "Content-Type: application/x-www-form-urlencoded", $sAdditionalData)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; See what's returned
Dim $sReturned
If _WinHttpQueryDataAvailable($hRequest) Then ; if there is data
Do
$sReturned &= _WinHttpReadData($hRequest)
Until @error
EndIf

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; See what's returned
MsgBox(4096, "Returned", $sReturned)
ConsoleWrite($sReturned & @CRLF)


Function Reference

_WinHttpSetCredentials

Passes the required authorization credentials to the server.

Syntax

#include "WinHttp.au3"
_WinHttpSetCredentials($hRequest, $iAuthTargets, $iAuthScheme, $sUserName, $sPassword)

Parameters

$hRequest | Valid handle returned by _WinHttpOpenRequest().
$iAuthTargets | Authentication target.
$iAuthScheme | Authentication scheme.
$sUserName | Valid user name.
$sPassword | Valid password.

Return Value

Success - Returns 1.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Related

_WinHttpOpenRequest

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; !!! The result of this script will be this sent to the server:
#cs

POST /admin.php HTTP/1.1
Connection: Keep-Alive
Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8
User-Agent: AutoIt/3.3
Content-Length: 0
Host: 127.0.0.1
Authorization: Basic YWRtaW46YWRtaW4=
#ce

; My server
Global $sLocalIP = "127.0.0.1"
; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sLocalIP)
; Specify the reguest
Global $hRequest = _WinHttpOpenRequest($hConnect, _
"POST", _ ; verb
"admin.php", _ ; object
Default, _ ; version
Default, _ ; referrer
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") ; accept types

; Set credentials
_WinHttpSetCredentials($hRequest, $WINHTTP_AUTH_TARGET_SERVER, $WINHTTP_AUTH_SCHEME_BASIC, "admin", "admin")

; Send request
_WinHttpSendRequest($hRequest)
; Wait for the response
_WinHttpReceiveResponse($hRequest)

; .... The rest of the code here...

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpSetDefaultProxyConfiguration

Sets the default WinHttp proxy configuration.

Syntax

#include "WinHttp.au3"
_WinHttpSetDefaultProxyConfiguration($iAccessType [, $sProxy = "" [, $sProxyBypass = ""])

Parameters

$iAccessType | Integer. Access type.
$sProxy | [optional] String. Proxy server list.
$sProxyBypass | [optional] String. Proxy bypass list.

Return Value

Success - Returns 1.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Related

_WinHttpDetectAutoProxyConfigUrl, _WinHttpGetDefaultProxyConfiguration, _WinHttpGetIEProxyConfigForCurrentUser

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Set No-proxy:
_WinHttpSetDefaultProxyConfiguration($WINHTTP_ACCESS_TYPE_NO_PROXY)

; ... the rest of the code here...


Function Reference

_WinHttpSetOption

Sets an Internet option.

Syntax

#include "WinHttp.au3"
_WinHttpSetOption($hInternet, $iOption, $vSetting [, $iSize = Default ])

Parameters

$hInternet | Handle on which to set data.
$iOption | Integer value that contains the Internet option to set.
$vSetting | Value of setting
$iSize | [optional] Size of $vSetting, required if $vSetting is pointer to memory block

Return Value

Success - Returns 1.
Failure - Returns 0 and sets @error:
1 - Invalid Internet option
2 - Size required
3 - Datatype of value does not fit to option
4 - DllCall failed

Related

_WinHttpQueryOption

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()

; Set User-Agent string
_WinHttpSetOption($hOpen, $WINHTTP_OPTION_USER_AGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)")

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "google.com")

; Specify the reguest:
Global $hRequest = _WinHttpOpenRequest($hConnect)

; Send request
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

Global $sHeader
; If there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header

; Clean
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; Display retrieved header
ConsoleWrite($sHeader & @CRLF)


Function Reference

_WinHttpSetStatusCallback

Sets up a callback function that WinHttp can call as progress is made during an operation.

Syntax

#include "WinHttp.au3"
_WinHttpSetStatusCallback($hInternet, $hInternetCallback [, $iNotificationFlags = Default ])

Parameters

$hInternet | Handle for which the callback is to be set.
$hInternetCallback | Callback function to call when progress is made.
$iNotificationFlags | [optional] Flags to indicate which events activate the callback function. Default is $WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS.

Return Value

Success - Returns a pointer to the previously defined status callback function or NULL if there was no previously defined status callback function.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Related

_WinHttpOpen

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Register Callback function
Global $hWINHTTP_STATUS_CALLBACK = DllCallbackRegister("__WINHTTP_STATUS_CALLBACK", "none", "handle;dword_ptr;dword;ptr;dword")
; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Associate callback function with this handle
_WinHttpSetStatusCallback($hOpen, $hWINHTTP_STATUS_CALLBACK)

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "google.com")
; Specify the reguest:
Global $hRequest = _WinHttpOpenRequest($hConnect)
; Send request
_WinHttpSendRequest($hRequest)
; Wait for the response
_WinHttpReceiveResponse($hRequest)

Global $sHeader
; If there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header

; Clean
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; Display retrieved header
ConsoleWrite(@CRLF & $sHeader & @CRLF)

; Sleep few seconds to see if there are more events
Sleep(2000)

; Free the callback when no longer needed (can be omitted in this case)
DllCallbackFree($hWINHTTP_STATUS_CALLBACK)

; Define callback function
Func __WINHTTP_STATUS_CALLBACK($hInternet, $iContext, $iInternetStatus, $pStatusInformation, $iStatusInformationLength)
#forceref $hInternet, $iContext, $pStatusInformation, $iStatusInformationLength
ConsoleWrite("!->Current status of the connection: " & $iInternetStatus & " " & @TAB & " ")
; Interpret the status
Local $sStatus
Switch $iInternetStatus
Case $WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
$sStatus = "Closing the connection to the server"
Case $WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
$sStatus = "Successfully connected to the server."
Case $WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
$sStatus = "Connecting to the server."
Case $WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
$sStatus = "Successfully closed the connection to the server."
Case $WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
$sStatus = "Data is available to be retrieved with WinHttpReadData."
Case $WINHTTP_CALLBACK_STATUS_HANDLE_CREATED
$sStatus = "An HINTERNET handle has been created."
Case $WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING
$sStatus = "This handle value has been terminated."
Case $WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
$sStatus = "The response header has been received and is available with WinHttpQueryHeaders."
Case $WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE
$sStatus = "Received an intermediate (100 level) status code message from the server."
Case $WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
$sStatus = "Successfully found the IP address of the server."
Case $WINHTTP_CALLBACK_STATUS_READ_COMPLETE
$sStatus = "Data was successfully read from the server."
Case $WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
$sStatus = "Waiting for the server to respond to a request."
Case $WINHTTP_CALLBACK_STATUS_REDIRECT
$sStatus = "An HTTP request is about to automatically redirect the request."
Case $WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
$sStatus = "An error occurred while sending an HTTP request."
Case $WINHTTP_CALLBACK_STATUS_REQUEST_SENT
$sStatus = "Successfully sent the information request to the server."
Case $WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
$sStatus = "Looking up the IP address of a server name."
Case $WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
$sStatus = "Successfully received a response from the server."
Case $WINHTTP_CALLBACK_STATUS_SECURE_FAILURE
$sStatus = "One or more errors were encountered while retrieving a Secure Sockets Layer (SSL) certificate from the server."
Case $WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
$sStatus = "Sending the information request to the server."
Case $WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
$sStatus = "The request completed successfully."
Case $WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
$sStatus = "Data was successfully written to the server."
EndSwitch
; Print it
ConsoleWrite($sStatus & @CRLF)
EndFunc ;==>__WINHTTP_STATUS_CALLBACK


Function Reference

_WinHttpSetTimeouts

Sets time-outs involved with HTTP transactions.

Syntax

#include "WinHttp.au3"
_WinHttpSetTimeouts($hInternet [, $iResolveTimeout = Default [, $iConnectTimeout = Default [, $iSendTimeout = Default [, $iReceiveTimeout = Default ]]]])

Parameters

$hInternet | Handle returned by _WinHttpOpen() or _WinHttpOpenRequest().
$iResolveTimeout | [optional] Time-out value, in milliseconds, to use for name resolution. Default is 0 ms.
$iConnectTimeout | [optional] Time-out value, in milliseconds, to use for server connection requests. Default is 60000 ms.
$iSendTimeout | [optional] Time-out value, in milliseconds, to use for sending requests. Default is 30000 ms.
$iReceiveTimeout | [optional] Time-out value, in milliseconds, to receive a response to a request. Default is 30000 ms.

Return Value

Success - Returns 1.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

Initial values are:
- $iResolveTimeout = 0
- $iConnectTimeout = 60000
- $iSendTimeout = 30000
- $iReceiveTimeout = 30000

Related

_WinHttpReceiveResponse

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Open needed handles
Global $hOpen = _WinHttpOpen()

; Set timeouts
_WinHttpSetTimeouts($hOpen, 10, 10, 10, 10)

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "msdn.microsoft.com")
; Specify the reguest:
Global $hRequest = _WinHttpOpenRequest($hConnect, Default, "en-us/library/aa384101(VS.85).aspx")

; Send request
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

Global $sHeader
; If there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then
$sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header
; Display retrieved header
MsgBox(0, "Header", $sHeader)
Else
; Display retrieved header
MsgBox(48, "Failure", "Maybe the new timeouts are unrealistic ;)")
EndIf

; Clean
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpSimpleBinaryConcat

Concatenates two binary data returned by _WinHttpReadData() in binary mode.

Syntax

#include "WinHttp.au3"
_WinHttpSimpleBinaryConcat(ByRef $bBinary1, ByRef $bBinary2)

Parameters

$bBinary1 | Binary data that is to be concatenated.
$bBinary2 | Binary data to concatenate.

Return Value

Success - Returns concatenated binary data.
Failure - Returns empty binary and sets @error:
1 - Invalid input.

Related

_WinHttpReadData

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

Global $sHost = "images.fanpop.com"
Global $sTarget = "images/image_uploads/Hello-Kitty-hello-kitty-181509_1024_768.jpg"
Global $sDestination = @ScriptDir & "\HelloKitty.jpg"

; Initialize and get session handle
Global $hHttpOpen = _WinHttpOpen()
If @error Then
MsgBox(48, "Error", "Error initializing the usage of WinHTTP functions.")
Exit 1
EndIf
; Get connection handle
Global $hHttpConnect = _WinHttpConnect($hHttpOpen, $sHost)
If @error Then
MsgBox(48, "Error", "Error specifying the initial target server of an HTTP request.")
_WinHttpCloseHandle($hHttpOpen)
Exit 2
EndIf
; Specify the reguest
Global $hHttpRequest = _WinHttpOpenRequest($hHttpConnect, Default, $sTarget)
If @error Then
MsgBox(48, "Error", "Error creating an HTTP request handle.")
_WinHttpCloseHandle($hHttpConnect)
_WinHttpCloseHandle($hHttpOpen)
Exit 3
EndIf
; Send request
_WinHttpSendRequest($hHttpRequest)
If @error Then
MsgBox(48, "Error", "Error sending specified request.")
_WinHttpCloseHandle($hHttpConnect)
_WinHttpCloseHandle($hHttpOpen)
Exit 4
EndIf

; Wait for the response
_WinHttpReceiveResponse($hHttpRequest)
; Read if available
Global $bChunk, $bData, $hFile
If _WinHttpQueryDataAvailable($hHttpRequest) Then
While 1
$bChunk = _WinHttpReadData($hHttpRequest, 2) ; read binary
If @error Then ExitLoop
$bData = _WinHttpSimpleBinaryConcat($bData, $bChunk) ; concat two binary data
WEnd
; Save it to the file
$hFile = FileOpen($sDestination, 26)
FileWrite($hFile, $bData)
FileClose($hFile)
Else
MsgBox(48, "Error occurred", "No data available. " & @CRLF)
EndIf

; Close handles
_WinHttpCloseHandle($hHttpRequest)
_WinHttpCloseHandle($hHttpConnect)
_WinHttpCloseHandle($hHttpOpen)

; See what's downloaded
ShellExecute($sDestination)


Function Reference

_WinHttpSimpleFormFill

Fills web form.

Syntax

#include "WinHttp.au3"
_WinHttpSimpleFormFill(ByRef $hInternet [, $sActionPage = Default [, $sFormId = Default [, $sFldId1 = Default [, $sDta1 = Default [, (...) [, $sAdditionalData]]]]]])

Parameters

$hInternet | Handle returned by _WinHttpConnect() or string variable with form.
$sActionPage | [optional] path to the page with form or session handle if $hInternet is string (default: "" - empty string; meaning 'default' page on the server in former).
$sFormId | [optional] Id of the form. Can be name or zero-based index too (read Remarks section).
$sFldId1 | [optional] Id of the input.
$sDta1 | [optional] Data to set to coresponding field.
(...) | [optional] Other pairs of Id/Data. Overall number of fields is 40.
$sAdditionalData | [optional] Additional data (read Remarks section).

Return Value

Success - Returns HTML source of the page returned by the server on submited form. @extended is set to HTTP status code.
Failure - Returns empty string and sets @error:
1 - No forms on the page
2 - Invalid form
3 - No forms with specified attributes on the page
4 - Connection problems
5 - form's "action" is invalid
6 - invalid session handle passed

Remarks

In case form requires redirection and $hInternet is internet handle, this handle will be closed and replaced with new and required one.
When $hInternet is form string, form's "action" must specify URL and $sActionPage parameter must be session handle. On succesful call this variable will be changed to connection handle of the internally made connection. Don't forget to close this handle after the function returns and when no longer needed.
$sFormId specifies Id of the form same as .getElementById(FormId). Aditionally you can use "index:FormIndex" to identify form by its zero-based index number (in case of e.g. three forms on some page first one will have index=0, second index=1, third index=2). Use "name:FormName" to identify form by its name like with .getElementsByName(FormName). FormName will be taken to be what's right of colon mark. In that case first form with that name is filled.
As for fields, If "name:FieldName" option is used all the fields except last with that name are removed from the form. Last one is filled with specified $sDta data.
This function can be used to fill forms with up to 40 fields at once.
"Submit" control you want to keep (click) set to True. If no such control is set then the first one found in the form is "clicked". You can also use "type:submit", zero_based_index_of_the_submit to "click" if no id or name is available.
All other "submit" controls are removed from the submited form (including images).
If form is submitted by clicking an image then pass click coordinates "name:image_name", "Xcoord,Ycoord" or "image_id", "Xcoord,Ycoord". If the image has no name or id then you can use its index of appearance "type:image", "zero_based_index_of_the_image Xcoord,Ycoord".
"Checkbox" and "Button" input types are removed from the submitted form unless explicitly set. Same goes for "Radio" with exception that only one such control can be set, the rest are removed. These controls are set by their values. Wrong value makes them invalid and therefore not part of the submited data.
All other non-set fields are left default.
Last (superfluous) $sAdditionalData argument can be used to pass authorization credentials in form "[CRED:username:password]", magic string to ignore certificate errors in form "[IGNORE_CERT_ERRORS]", change output type to extended array with "[RETURN_ARRAY]" moniker, and/or HTTP request header data to add. If array is returned then array[0] is the response header, array[1] is returned data and array[2] is URL of the final request.

If this function is used to upload multiple files then there are two available ways. Default would be to submit the form following RFC2388 specification. In that case every file is represented as multipart/mixed part embedded within the multipart/form-data.
If you want to upload using alternative way (to avoid certain PHP bug that could exist on server side) then prefix the file string with "PHP#50338:" string.
For example: ..."name:files[]", "PHP#50338:" & $sFile1 & "|" & $sFile2 ...
Muliple files are always separated with vertical line ASCII character when filling the form.

Related

_WinHttpConnect, _WinHttpSimpleFormFill_SetUploadCallback

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

Global $hOpen, $hConnect
Global $sRead, $hFileHTM, $sFileHTM = @ScriptDir & "\Form.htm"

; Example1:
; 1. Open APNIC whois page (http://wq.apnic.net/apnic-bin/whois.pl)
; 2. Fill form on that page with these values/conditins:
; - fill default form
; - set ip address 4.2.2.2 to input box. Use name propery to locate input
; - send form (click button)
; - gather returned data

; Initialize and get session handle
$hOpen = _WinHttpOpen()
; Get connection handle
$hConnect = _WinHttpConnect($hOpen, "wq.apnic.net")
; Fill form on this page
$sRead = _WinHttpSimpleFormFill($hConnect, "apnic-bin/whois.pl", Default, "name:searchtext", "4.2.2.2", "name:object_type", "All")
; Close connection handle
_WinHttpCloseHandle($hConnect)
; Close session handle
_WinHttpCloseHandle($hOpen)

; See what's returned (in default browser or whatever)
If $sRead Then
MsgBox(64 + 262144, "Done!", "Will open returned page in your default browser now.")
$hFileHTM = FileOpen($sFileHTM, 2)
FileWrite($hFileHTM, $sRead)
FileClose($hFileHTM)
ShellExecuteWait($sFileHTM)
EndIf

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

Global $hOpen, $hConnect
Global $sRead, $hFileHTM, $sFileHTM = @ScriptDir & "\Form.htm"

; Example 2:
; 1. Open w3schools forms page (http://www.w3schools.com/html/html_forms.asp)
; 2. Fill form on that page with these values/conditins:
; - form is to be identified by its index -0-
; - set -Miyake- and -Issey- data to input boxes. Locate input boxes by their names -firstname- and -lastname-

; Initialize and get session handle
$hOpen = _WinHttpOpen()
; Get connection handle
$hConnect = _WinHttpConnect($hOpen, "w3schools.com")
; Fill form on this page
$sRead = _WinHttpSimpleFormFill($hConnect, "html/html_forms.asp", "index:0", "name:firstname", "Miyake", "name:lastname", "Issey")
; Close connection handle
_WinHttpCloseHandle($hConnect)
; Close session handle
_WinHttpCloseHandle($hOpen)

If $sRead Then
MsgBox(64 + 262144, "Done!", "Will open returned page in your default browser now." & @CRLF & _
"You should see 'Miyake Issey' somewhere on that page.")
$hFileHTM = FileOpen($sFileHTM, 2)
FileWrite($hFileHTM, $sRead)
FileClose($hFileHTM)
ShellExecuteWait($sFileHTM)
EndIf

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

Dim $hOpen, $hConnect
Dim $sRead

; Example 3:
; 1. Open cs.tut.fi forms page (http://www.cs.tut.fi/~jkorpela/forms/testing.html)
; 2. Fill form on that page with these values/conditins:
; - form is to be identified by its index, It's first form on the page, i.e. index is 0
; - set -Johnny B. Goode- data to textarea. Locate it by its name -Comments-.
; - check the checkbox. Locate it by name -box-. Checked value is -yes-.
; - set -This is hidden, so what?- data to input field identified by name -hidden field-.
; - gather data

; Initialize and get session handle
$hOpen = _WinHttpOpen()
; Get connection handle
$hConnect = _WinHttpConnect($hOpen, "www.cs.tut.fi")
; Fill form on this page
$sRead = _WinHttpSimpleFormFill($hConnect, _ ; connection handle
"~jkorpela/forms/testing.html", _ ; target page
"index:0", _ ; form identifier
"name:Comments", "Johnny B. Goode", _ ; first field identifier paired with field data
"name:box", "yes", _ ; second field identifier paired with data
"name:hidden field", "This is hidden, so what?") ; third field identifier paired with data
; Close connection handle
_WinHttpCloseHandle($hConnect)
; Close session handle now that's no longer needed
_WinHttpCloseHandle($hOpen)

If $sRead Then
ConsoleWrite($sRead & @CRLF)
MsgBox(64 + 262144, "Web Page says", $sRead)
EndIf

Copy to clipboard

#include "WinHttp.au3"

$sAddress = "https://posttestserver.com/post.php?dump&dir=WinHttp" ; the address of the target (https or http, makes no difference - handled automatically)

$sFileToUpload = @ScriptFullPath ; upload itself

$sForm = _
'<form action="' & $sAddress & '" method="post" enctype="multipart/form-data">' & _
' <input type="file" name="upload"/>' & _ ;
' <input type="text" name="someparam" />' & _
'</form>'

; Initialize and get session handle
$hOpen = _WinHttpOpen()

$hConnect = $sForm ; will pass form as string so this is for coding correctness because $hConnect goes in byref

; Fill form
$sHTML = _WinHttpSimpleFormFill($hConnect, $hOpen, _
Default, _
"name:upload", $sFileToUpload, _
"name:someparam", "Candy")

If @error Then
MsgBox(4096, "Error", "Error number = " & @error)
Else
ConsoleWrite($sHTML & @CRLF)
EndIf

; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

Copy to clipboard

#include <Array.au3>
#include "WinHttp.au3"

; Example 5:
; 1. Open www.cs.tut.fi forms page (https://www.cs.tut.fi/~jkorpela/forms/testing.html)
; 2. Fill form on that page with these values/conditins:
; - form is to be identified by its index -1-
; - set -Something- and -this script- data to input boxes. Locate input boxes by their names -textfield- and -filefield-
; 2. Return array

; Initialize and get session handle
$hOpen = _WinHttpOpen()
; Get connection handle
$hConnect = _WinHttpConnect($hOpen, "https://www.cs.tut.fi")
; Fill form on this page
$aRead = _WinHttpSimpleFormFill($hConnect, "~jkorpela/forms/testing.html", _
"index:1", _
"name:textfield", "Testing file upload", _
"name:filefield", @ScriptFullPath, _
"[RETURN_ARRAY]")

; Close connection handle
_WinHttpCloseHandle($hConnect)
; Close session handle
_WinHttpCloseHandle($hOpen)

_ArrayDisplay($aRead)

Copy to clipboard

#include "WinHttp.au3"

; Example 5:
; 1. Open try.coderlearner.com form-action page (http://try.coderlearner.com/html5/form/form_formaction_ex_2.html)
; 2. Fill form on that page with these values/conditins:
; - form is default one
; - set -User- and -Password- data to input boxes. Locate input boxes by their names -loginName- and -loginPass-
; - click third button (register action)

; Initialize and get session handle
$hOpen = _WinHttpOpen()
; Get connection handle
$hConnect = _WinHttpConnect($hOpen, "http://try.coderlearner.com")
; Fill form on this page
$aRead = _WinHttpSimpleFormFill($hConnect, "html5/form/form_formaction_ex_2.html", _
Default, _
"name:loginName", "User", _
"name:loginPass", "Password", _
"type:submit", 2 _ ; third button (zero-based counting scheme)
)
; Close connection handle
_WinHttpCloseHandle($hConnect)
; Close session handle
_WinHttpCloseHandle($hOpen)

MsgBox(4096, "Returned", $aRead)


Function Reference

_WinHttpSimpleFormFill_SetUploadCallback

Sets user defined function as callback function for _WinHttpSimpleFormFill

Syntax

#include "WinHttp.au3"
_WinHttpSimpleFormFill_SetUploadCallback($vCallback [, $iNumChunks = 100 ])

Parameters

$vCallback | UDF's name
$iNumChunks | [optional] number of chunks to send during form submitting. Default is 100.

Return Value

Undefined.

Remarks

Unregistering is done by passing 0 as first argument.

Related

_WinHttpSimpleFormFill

Example

Copy to clipboard

#include "WinHTTP.au3"

$sAddress = "https://posttestserver.com/post.php?dir=WinHttp" ; the address of the target (https or http, makes no difference - handled automatically)

; Select some file
$sFileToUpload = FileOpenDialog("Select file to upload...", "", "All Files (*)")
If Not $sFileToUpload Then Exit 5 ; check if the file is selected and exit if not

$sForm = _
'<form action="' & $sAddress & '" method="post" enctype="multipart/form-data">' & _
' <input type="file" name="upload"/>' & _
'</form>'

; Initialize and get session handle
$hOpen = _WinHttpOpen()

$hConnect = $sForm ; will pass form as string so this is for coding correctness because $hConnect goes in byref

; Creates progress bar window
ProgressOn("UPLOADING", $sFileToUpload, "0%")

; Register callback function
_WinHttpSimpleFormFill_SetUploadCallback(UploadCallback)

; Fill form
$sHTML = _WinHttpSimpleFormFill($hConnect, $hOpen, _
Default, _
"name:upload", $sFileToUpload)
; Collect error number
$iErr = @error

; Unregister callback function
_WinHttpSimpleFormFill_SetUploadCallback(0)

; Kill progress bar window
ProgressOff()

; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

If $iErr Then
MsgBox(4096, "Error", "Error number = " & $iErr)
Else
ConsoleWrite($sHTML & @CRLF)
MsgBox(4096, "Success", $sHTML)
EndIf

; Callback function. For example, update progress control
Func UploadCallback($iPrecent)
If $iPrecent = 100 Then
ProgressSet(100, "Done", "Complete")
Sleep(800) ; give some time for the progress bar to fill-in completely
Else
ProgressSet($iPrecent, $iPrecent & "%")
EndIf
EndFunc


Function Reference

_WinHttpSimpleReadData

Reads data from a request

Syntax

#include "WinHttp.au3"
_WinHttpSimpleReadData($hRequest [, $iMode = Default ])

Parameters

$hRequest | request handle after _WinHttpReceiveResponse
$iMode | [optional] type of data returned

Return Value

Success - String or binary depending on $iMode
Failure - empty string or empty binary (mode 2) and set @error
1 - invalid mode
2 - no data available

Remarks

In case of default reading mode, if the server specifies utf-8 content type, function will force UTF-8 string.

Related

_WinHttpReadData, _WinHttpSimpleRequest, _WinHttpSimpleSSLRequest

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "thetimes.co.uk")
; Request
Global $hRequest = _WinHttpSimpleSendRequest($hConnect)

; Simple-read...
Global $sRead = _WinHttpSimpleReadData($hRequest)
MsgBox(64, "Returned (first 1100 characters)", StringLeft($sRead, 1100) & "...")

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpSimpleReadDataAsync

Reads data from a request in asynchronous mode

Syntax

#include "WinHttp.au3"
_WinHttpSimpleReadDataAsync($hInternet, Byref $pBuffer [, $iNumberOfBytesToRead = Default ])

Parameters

$hInternet | Request handle (first parameter while in callback function).
$pBuffer | Pointer to memory buffer to which to read.
$iNumberOfBytesToRead | [optional] The number of bytes to read. Default is 8192 bytes.

Return Value

Same as for _WinHttpReadData. Due to async nature here it has no meaning except in case of possible error.

Remarks

You are strongly discouraged to use WinHTTP in asynchronous mode with AutoIt. AutoIt's callback implementation can't handle reentrancy properly.
WinHttp is rentrant during asynchronous completion callback. Make sure you have only one callback running and only one request handled though it at time.
Also make sure memory buffer is at least 8192 bytes in size if $iNumberOfBytesToRead is left default.

Related

_WinHttpSimpleReadData, _WinHttpReadData

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
; Reserve memory space for asynchronous work
;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
; The size
Global Const $iSizeBufferAsync = 1048576 ; 1MB for example, should be enough
; The buffer
Global Static $tBufferAsync = DllStructCreate("byte[" & $iSizeBufferAsync & "]")
; Get pointer to this memory space
Global $pBufferAsync = DllStructGetPtr($tBufferAsync)

; Register Callback function
Global $hWINHTTP_STATUS_CALLBACK = DllCallbackRegister("__WINHTTP_STATUS_CALLBACK", "none", "handle;dword_ptr;dword;ptr;dword")

; Initialize and get session handle. Asynchronous flag.
Global $hOpen = _WinHttpOpen(Default, Default, Default, Default, $WINHTTP_FLAG_ASYNC)

; Assign callback function
_WinHttpSetStatusCallback($hOpen, $hWINHTTP_STATUS_CALLBACK)

; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "msdn.microsoft.com")

; Make request
Global $hRequest = _WinHttpOpenRequest($hConnect, Default, "en-us/library/aa383917(v=vs.85).aspx")

; Send it
_WinHttpSendRequest($hRequest)

; Some dummy code for waiting
MsgBox(64 + 262144, "Wait...", "Wait for the results if they are not shown already.")

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)
; Free callback. Redundant here
DllCallbackFree($hWINHTTP_STATUS_CALLBACK)

;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
; Define callback function
;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Func __WINHTTP_STATUS_CALLBACK($hInternet, $iContext, $iInternetStatus, $pStatusInformation, $iStatusInformationLength)
#forceref $hInternet, $iContext, $pStatusInformation, $iStatusInformationLength
ConsoleWrite(">> ")
; Interpret the status
Local $sStatus
Switch $iInternetStatus
Case $WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION
$sStatus = "Closing the connection to the server"
Case $WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER
$sStatus = "Successfully connected to the server."
Case $WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER
$sStatus = "Connecting to the server."
Case $WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED
$sStatus = "Successfully closed the connection to the server."
Case $WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
$sStatus = "Data is available to be retrieved with WinHttpReadData."
ConsoleWrite($sStatus & @CRLF)

;*************************************
; Read asynchronously
;*************************************
_WinHttpSimpleReadDataAsync($hInternet, $pBufferAsync, $iSizeBufferAsync)
Return

Case $WINHTTP_CALLBACK_STATUS_HANDLE_CREATED
$sStatus = "An HINTERNET handle has been created: " & $hInternet
Case $WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING
$sStatus = "This handle value has been terminated: " & $hInternet
Case $WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
$sStatus = "The response header has been received and is available with WinHttpQueryHeaders."
ConsoleWrite($sStatus & @CRLF)

;*************************************
; Print header
;*************************************
ConsoleWrite(_WinHttpQueryHeaders($hInternet) & @CRLF)

;*************************************
; Check if there is any data available
;*************************************
_WinHttpQueryDataAvailable($hInternet)

Return

Case $WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE
$sStatus = "Received an intermediate (100 level) status code message from the server."
Case $WINHTTP_CALLBACK_STATUS_NAME_RESOLVED
$sStatus = "Successfully found the IP address of the server."
Case $WINHTTP_CALLBACK_STATUS_READ_COMPLETE
$sStatus = "Data was successfully read from the server."
ConsoleWrite($sStatus & @CRLF)

;*************************************
; Print read data
;*************************************
Local $sRead = DllStructGetData(DllStructCreate("char[" & $iStatusInformationLength & "]", $pStatusInformation), 1)
ConsoleWrite($sRead & @CRLF)

Return

Case $WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE
$sStatus = "Waiting for the server to respond to a request."
Case $WINHTTP_CALLBACK_STATUS_REDIRECT
$sStatus = "An HTTP request is about to automatically redirect the request."
Case $WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
$sStatus = "An error occurred while sending an HTTP request."
Case $WINHTTP_CALLBACK_STATUS_REQUEST_SENT
$sStatus = "Successfully sent the information request to the server."
Case $WINHTTP_CALLBACK_STATUS_RESOLVING_NAME
$sStatus = "Looking up the IP address of a server name."
Case $WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED
$sStatus = "Successfully received a response from the server."
Case $WINHTTP_CALLBACK_STATUS_SECURE_FAILURE
$sStatus = "One or more errors were encountered while retrieving a Secure Sockets Layer (SSL) certificate from the server."
Case $WINHTTP_CALLBACK_STATUS_SENDING_REQUEST
$sStatus = "Sending the information request to the server."
Case $WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
$sStatus = "The request completed successfully."
ConsoleWrite($sStatus & @CRLF)

;*************************************
; Receive Response
;*************************************
_WinHttpReceiveResponse($hInternet)
Return

Case $WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
$sStatus = "Data was successfully written to the server."
EndSwitch
; Print it
ConsoleWrite($sStatus & @CRLF)
EndFunc ;==>__WINHTTP_STATUS_CALLBACK


Function Reference

_WinHttpSimpleRequest

A function to send a request in a simpler form

Syntax

#include "WinHttp.au3"
_WinHttpSimpleRequest($hConnect, $sType, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default ]]]]])

Parameters

$hConnect | Handle from _WinHttpConnect
$sType | [optional] GET or POST (default: GET)
$sPath | [optional] request path (default: "" - empty string; meaning 'default' page on the server)
$sReferrer | [optional] referrer (default: $WINHTTP_NO_REFERER)
$sDta | [optional] POST-Data (default: $WINHTTP_NO_REQUEST_DATA)
$sHeader | [optional] additional Headers (default: $WINHTTP_NO_ADDITIONAL_HEADERS)
$fGetHeaders | [optional] return response headers (default: False)
$iMode | [optional] reading mode of result

Return Value

Success - response data if $fGetHeaders = False (default)
Array if $fGetHeaders = True
[0] - response headers
[1] - response data
Failure - 0 and set @error
1 - could not open request
2 - could not send request
3 - could not receive response
4 - $iMode is not valid

Related

_WinHttpSimpleSSLRequest, _WinHttpSimpleSendRequest, _WinHttpSimpleSendSSLRequest, _WinHttpQueryHeaders, _WinHttpSimpleReadData

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.9.0.3; .NET CLR 2.0.50727; ffco7) Gecko/2008092417 Firefox/3.0.3")
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "autoit.de")

; Simple-request it...
MsgBox(64, "Returned (first 1400 characters)", StringLeft(_WinHttpSimpleRequest($hConnect), 1400) & "...")

; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpSimpleSendRequest

A function to send a request in a simpler form, but not read the data

Syntax

#include "WinHttp.au3"
_WinHttpSimpleSendRequest($hConnect, $sType, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default ]]])

Parameters

$hConnect | Handle from _WinHttpConnect
$sType | [optional] GET or POST (default: GET)
$sPath | [optional] request path (default: "" - empty string; meaning 'default' page on the server)
$sReferrer | [optional] referrer (default: $WINHTTP_NO_REFERER)
$sDta | [optional] POST-Data (default: $WINHTTP_NO_REQUEST_DATA)
$sHeader | [optional] additional Headers (default: $WINHTTP_NO_ADDITIONAL_HEADERS)

Return Value

Success - handle of request after _WinHttpReceiveResponse.
Failure - 0 and set @error
1 - could not open request
2 - could not send request
3 - could not receive response

Related

_WinHttpSimpleRequest, _WinHttpSimpleSendSSLRequest, _WinHttpSimpleReadData

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "w3schools.com")
; Make a request
Global $hRequest = _WinHttpSimpleSendRequest($hConnect, Default, "tags/tag_input.asp")

If $hRequest Then
; Simple-read...
ConsoleWrite(_WinHttpSimpleReadData($hRequest) & @CRLF)
MsgBox(64, "Okey do!", "Returned source is print to concole. Check it.")
Else
MsgBox(48, "Error", "Error ocurred for _WinHttpSimpleSendRequest, Error number is " & @error)
EndIf

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Function Reference

_WinHttpSimpleSendSSLRequest

A function to send a SSL request in a simpler form, but not read the data

Syntax

#include "WinHttp.au3"
_WinHttpSimpleSendSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default ]]]]])

Parameters

$hConnect | Handle from _WinHttpConnect
$sType | [optional] GET or POST (default: GET)
$sPath | [optional] request path (default: "" - empty string; meaning 'default' page on the server)
$sReferrer | [optional] referrer (default: $WINHTTP_NO_REFERER)
$sDta | [optional] POST-Data (default: $WINHTTP_NO_REQUEST_DATA)
$sHeader | [optional] additional Headers (default: $WINHTTP_NO_ADDITIONAL_HEADERS)

Return Value

Success - handle of request after _WinHttpReceiveResponse.
Failure - 0 and set @error
1 - could not open request
2 - could not send request
3 - could not receive response

Related

_WinHttpSimpleSSLRequest, _WinHttpSimpleSendRequest, _WinHttpSimpleReadData

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Windows Live ID. JavaScript required to sign in, remember that.
Global $sDomain = "accountservices.passport.net"
Global $sPage = "uiresetpw.srf"

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sDomain)

; Make a SimpleSSL request
Global $hRequestSSL = _WinHttpSimpleSendSSLRequest($hConnect, Default, $sPage)

; Read...
Global $sReturned = _WinHttpSimpleReadData($hRequestSSL)
; Close handles
_WinHttpCloseHandle($hRequestSSL)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; See what's returned
ConsoleWrite($sReturned & @CRLF)
MsgBox(64 + 262144, "Done", "Page source is printed to console")


Function Reference

_WinHttpSimpleSSLRequest

A function to send a SSL request in a simpler form

Syntax

#include "WinHttp.au3"
_WinHttpSimpleSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default ]]]]]]])

Parameters

$hConnect | Handle from _WinHttpConnect
$sType | [optional] GET or POST (default: GET)
$sPath | [optional] request path (default: "" - empty string; meaning 'default' page on the server)
$sReferrer | [optional] referrer (default: $WINHTTP_NO_REFERER)
$sDta | [optional] POST-Data (default: $WINHTTP_NO_REQUEST_DATA)
$sHeader | [optional] additional Headers (default: $WINHTTP_NO_ADDITIONAL_HEADERS)
$fGetHeaders | [optional] return response headers (default: False)
$iMode | [optional] reading mode of result

Return Value

Success - response data if $fGetHeaders = False (default)
Array if $fGetHeaders = True
[0] - response headers
[1] - response data
Failure - 0 and set @error
1 - could not open request
2 - could not send request
3 - could not receive response
4 - $iMode is not valid

Related

_WinHttpSimpleRequest, _WinHttpSimpleSendSSLRequest, _WinHttpSimpleSendRequest, _WinHttpQueryHeaders, _WinHttpSimpleReadData

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; !!!Note that this example will fail because of invalid username and password!!!

; Use real data for authentication
Global $sUserName = "SomeUserName"
Global $sPassword = "SomePassword"
Global $sDomain = "www.google.com"
Global $sPage = "accounts/ClientLogin"
; Visit http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html for more informations
Global $sAdditionalData = "accountType=HOSTED_OR_GOOGLE&Email=" & $sUserName & "&Passwd=" & $sPassword & "&service=mail&source=Gulp-CalGulp-1.05"

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sDomain)

; SimpleSSL-request it...
Global $sReturned = _WinHttpSimpleSSLRequest($hConnect, "POST", $sPage, Default, $sAdditionalData)

; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; See what's returned
MsgBox(0, "Returned", $sReturned)


Function Reference

_WinHttpTimeFromSystemTime

Formats a system date and time according to the HTTP version 1.0 specification.

Syntax

#include "WinHttp.au3"
_WinHttpTimeFromSystemTime()

Parameters

None.

Return Value

Success - Returns time string.
Failure - Returns empty string and sets @error:
1 - Initial DllCall failed
2 - Main DllCall failed

Related

_WinHttpTimeToSystemTime

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

MsgBox(64, "WinHttp time", _WinHttpTimeFromSystemTime())


Function Reference

_WinHttpTimeToSystemTime

Takes an HTTP time/date string and converts it to array (SYSTEMTIME structure values).

Syntax

#include "WinHttp.au3"
_WinHttpTimeToSystemTime($sHttpTime)

Parameters

$sHttpTime Date/time string to convert.

Return Value

Success - Returns array with 8 elements:
$array[0] - Year,
$array[1] - Month,
$array[2] - DayOfWeek,
$array[3] - Day,
$array[4] - Hour,
$array[5] - Minute,
$array[6] - Second.,
$array[7] - Milliseconds.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Related

_WinHttpTimeFromSystemTime

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"
#include <Array.au3>

Opt("MustDeclareVars", 1)

; Time
Global $aTime = _WinHttpTimeToSystemTime("Sat, 21 Aug 2010 22:04:43 GMT")
_ArrayDisplay($aTime, "_WinHttpTimeToSystemTime()")


Function Reference

_WinHttpWriteData

Writes request data to an HTTP server.

Syntax

#include "WinHttp.au3"
_WinHttpWriteData($hRequest, $vData [, $iMode = Default ])

Parameters

$hRequest | Valid handle returned by _WinHttpSendRequest().
$vData | Data to write.
$iMode | [optional] Integer representing writing mode. Default is 0 - write ANSI string.

Return Value

Success - Returns 1
- @extended receives the number of bytes written.
Failure - Returns 0 and sets @error:
1 - DllCall failed

Remarks

$vData variable is either string or binary data to write. $iMode can have these values:
0 - to write ANSI string
1 - to write binary data

Related

_WinHttpSendRequest, _WinHttpReadData

See Also

MSDN

Example

Copy to clipboard

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, "httpbin.org")
; Specify the reguest
Global $hRequest = _WinHttpOpenRequest($hConnect, "POST", "/post")

Global $sPostData = "Additional data to send"
; Send request
_WinHttpSendRequest($hRequest, Default, Default, StringLen($sPostData))

; Write additional data to send
_WinHttpWriteData($hRequest, $sPostData)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

; Check if there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then
MsgBox(64, "OK", _WinHttpReadData($hRequest))
Else
MsgBox(48, "Error", "Site is experiencing problems (or you).")
EndIf

; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


Functions

Function Reference

Below is a complete list of the Functions available in WinHttp.
Click on a function name for a detailed description.

Function | Description
_WinHttpAddRequestHeaders | Adds one or more HTTP request headers to the HTTP request handle.
_WinHttpCheckPlatform | Determines whether the current platform is supported by this version of Microsoft Windows HTTP Services (WinHTTP).
_WinHttpCloseHandle | Closes a single handle.
_WinHttpConnect | Specifies the initial target server of an HTTP request and returns connection handle to an HTTP session for that initial target.
_WinHttpCrackUrl | Separates a URL into its component parts such as host name and path.
_WinHttpCreateUrl | Creates a URL from array of components such as the host name and path.
_WinHttpDetectAutoProxyConfigUrl | Finds the URL for the Proxy Auto-Configuration (PAC) file.
_WinHttpGetDefaultProxyConfiguration | Retrieves the default WinHttp proxy configuration.
_WinHttpGetIEProxyConfigForCurrentUser | Retrieves the Internet Explorer proxy configuration for the current user.
_WinHttpOpen | Initializes the use of WinHttp functions and returns a WinHttp-session handle.
_WinHttpOpenRequest | Creates an HTTP request handle.
_WinHttpQueryAuthSchemes | Returns the authorization schemes that are supported by the server.
_WinHttpQueryDataAvailable | Returns the availability to be read with _WinHttpReadData().
_WinHttpQueryHeaders | Retrieves header information associated with an HTTP request.
_WinHttpQueryOption | Queries an Internet option on the specified handle.
_WinHttpReadData | Reads data from a handle opened by the _WinHttpOpenRequest() function.
_WinHttpReceiveResponse | Waits to receive the response to an HTTP request initiated by WinHttpSendRequest().
_WinHttpSendRequest | Sends the specified request to the HTTP server.
_WinHttpSetCredentials | Passes the required authorization credentials to the server.
_WinHttpSetDefaultProxyConfiguration | Sets the default WinHttp proxy configuration.
_WinHttpSetOption | Sets an Internet option.
_WinHttpSetStatusCallback | Sets up a callback function that WinHttp can call as progress is made during an operation.
_WinHttpSetTimeouts | Sets time-outs involved with HTTP transactions.
_WinHttpSimpleBinaryConcat | Concatenates two binary data returned by _WinHttpReadData() in binary mode.
_WinHttpSimpleFormFill | Fills web form.
_WinHttpSimpleFormFill_SetUploadCallback | Sets user defined function as callback function for _WinHttpSimpleFormFill
_WinHttpSimpleReadData | Reads data from a request
_WinHttpSimpleReadDataAsync | Reads data from a request in asynchronous mode
_WinHttpSimpleRequest | A function to send a request in a simpler form
_WinHttpSimpleSendRequest | A function to send a request in a simpler form, but not read the data
_WinHttpSimpleSendSSLRequest | A function to send a SSL request in a simpler form, but not read the data
_WinHttpSimpleSSLRequest | A function to send a SSL request in a simpler form
_WinHttpTimeFromSystemTime | Formats a system date and time according to the HTTP version 1.0 specification.
_WinHttpTimeToSystemTime | Takes an HTTP time/date string and converts it to array (SYSTEMTIME structure values).
_WinHttpWriteData | Writes request data to an HTTP server.


Tetris

Click to rotate (R)
Level:
Lines:
Points:
by Charles Tio


TOC

  • WinHttp Function Notes
  • Functions
  • _WinHttpAddRequestHeaders
  • _WinHttpCheckPlatform
  • _WinHttpCloseHandle
  • _WinHttpConnect
  • _WinHttpCrackUrl
  • _WinHttpCreateUrl
  • _WinHttpDetectAutoProxyConfigUrl
  • _WinHttpGetDefaultProxyConfiguration
  • _WinHttpGetIEProxyConfigForCurrentUser
  • _WinHttpOpen
  • _WinHttpOpenRequest
  • _WinHttpQueryAuthSchemes
  • _WinHttpQueryDataAvailable
  • _WinHttpQueryHeaders
  • _WinHttpQueryOption
  • _WinHttpReadData
  • _WinHttpReceiveResponse
  • _WinHttpSendRequest
  • _WinHttpSetCredentials
  • _WinHttpSetDefaultProxyConfiguration
  • _WinHttpSetOption
  • _WinHttpSetStatusCallback
  • _WinHttpSetTimeouts
  • _WinHttpSimpleBinaryConcat
  • _WinHttpSimpleFormFill
  • _WinHttpSimpleFormFill_SetUploadCallback
  • _WinHttpSimpleReadData
  • _WinHttpSimpleReadDataAsync
  • _WinHttpSimpleRequest
  • _WinHttpSimpleSendRequest
  • _WinHttpSimpleSendSSLRequest
  • _WinHttpSimpleSSLRequest
  • _WinHttpTimeFromSystemTime
  • _WinHttpTimeToSystemTime
  • _WinHttpWriteData