Cry about...
Delphi Programming
FTP programming with the WinInet API
These notes are not intended as a complete guide to the WinInet API,
but are provided for guidance when developing FTP applications with Delphi
that use the WinInet API. A full list of functions may be found at
http://msdn.microsoft.com/en-us/library/aa385473(VS.85).aspx
or by examining the Delphi file WinInet.pas
.
FTP functions provided by the Win32 Windows Internet (WinInet) API:
Function Description FtpCommand Issues an FTP comment on the server. FtpCreateDirectory Creates a new directory on the server. FtpDeleteFile Deletes the specified file from the server. FtpFindFirstFile Starts a wildcard file search of a directory on the server. FtpGetCurrentDirectory Retrieves the current working directory on the server. FtpGetFile Copies a file from the server to a local directory. FtpGetFileSize Returns the size of a previously opened file from the server. FtpOpenFile Opens a file on the server. FtpPutFile Copies a local file to the server. FtpRemoveDirectory Deletes a directory from the server. FtpRenameFile Renames the specified file on the server. FtpSetCurrentDirectory Sets the current working directory on the server. HttpQueryInfo Retrieves response header information associated with a HTTP request. InternetAttemptConnect Attempts to make a connection to the Internet. InternetCloseHandle Closes an internet handle. InternetConnect Opens a session for FTP, HTTP or Gopher application. InternetDial Dials a connection using a modem. InternetGetConnectedState Retrieves the connection state of the local system. InternetGetConnectedStateEx Retrieves the connection state of the local system. InternetGetLastResponseInfo Returns the text of the last WinInet error or server response. InternetFindNextFile Used to continue a search started with FtpFindFirstFile. InternetHangUp Hangs up a modem connection. InternetOpen Initialises the WinInet API. InternetOpenUrl Opens an FTP, Gopher or HTTP resource. InternetReadFile Reads data from an open handle. InternetSetOption Sets a WinInet configuration option. InternetSetStatusCallback Sets a callback function used to provide feedback during asynchronous use of the WinInet API.
Function definitions and types are defined in the unit "WinInet". WinInet errors are listed in a separate note, follow this link to view WinInet errors.
FtpCommand
Issues an FTP command on the server. (If you are used to using the command line version of FTP, this equates to the FTP "literal" command.)
function FtpCommand( hConnect: HINTERNET; fExpectResponse: BOOL; dwFlags: DWORD; lpszCommand: PChar; dwContext: DWORD; var phFtpCommand: HINTERNET): BOOL;
Parameters:
hConnect
- Connection handle for the current FTP session.
fExpectResponse
- Flag indicating whether (a stream of) data is expected back in response to the command.
dwFlags
- Flags affecting the behaviour of the function. Use 0 or one of:
FTP_TRANSFER_TYPE_ASCII
- File/data transfer in ascii.
FTP_TRANSFER_TYPE_BINARY
- File/data transfer in binary mode.
lpszCommand
- The FTP command to execute on the server. The server response can be read by calling
InternetGetLastResponseInfo
.dwContext
- Application defined value, which is used only if the application has already called
InternetSetStatusCallback
to set up a callback. Otherwise use 0.phFtpCommand
- Pointer to handle that will be created for response data, only created if fExpectResponse is true. Use
InternetReadFile
to read the data returned.
Returns: True if successful, False otherwise. The actual error code is
returned by a call to GetLastError()
.
Note:
- The FTP acknowledgement from the server can be read using
InternetGetLastResponseInfo
. - In Delphi 5, 6 and 7 (and possibly other versions besides) the function
definition provided in WinInet is incorrect and is missing the last
parameter '
phFtpCommand
'. The correct definition is:
function FtpCommand( hConnect: HINTERNET; fExpectResponse: BOOL; dwFlags: DWORD; lpszCommand: PChar; dwContext: DWORD; var phFtpCommand: PHINTERNET): BOOL; stdcall; external 'wininet.dll' name 'FtpCommandA';
- If there is any data content (such as a directory listing) then
you must set
fExpectResponse
true and read the data (even if you ultimately discard it). SettingfExpectResponse
to true when there is no data content will result in a call toInternetReadFile
hanging until it eventually times-out. - Follow this link for an
example of using
FtpCommand
. - For a list of possible commands see: http://www.nsftools.com/tips/RawFTP.htm.
- Tip: Include a call to InternetGetLastResponseInfo immediately after FtpCommand - even if you are expecting a stream of data (i.e. if fExpectResponse=true). Without this any server response returned is likely to cause WinInet to get out of sync - and stop working!
FtpCreateDirectory
Creates a new directory on the server.
function FtpCreateDirectory( hConnect: HINTERNET; lpszDirectory: PChar): BOOL;
FtpDeleteFile
Deletes the specified file from the server.
function FtpDeleteFile( hConnect: HINTERNET; lpszFileName: PChar): BOOL;
FtpFindFirstFile
Starts a new wildcard file search of a directory on the server, returning details of the first of the files found.
function FtpFindFirstFile( hConnect: HINTERNET; lpszSearchFile: PChar; var lpFindFileData: TWin32FindData; dwFlags: DWORD; dwContext: DWORD): HINTERNET;
Parameters:
hConnect
- Connection handle for the current FTP session.
lpszSearchFile
- Pointer to a null terminated string that specifies the directory path or file spec. May contain wildcards. If NIL or empty then it will match against all the files in the current server directory.
lpFindFileData
- Pointer to the record that will receive details of the first matching file.
dwFlags
- Flags affecting the behaviour of the function. Use 0 or one of:
INTERNET_FLAG_HYPERLINK
INTERNET_FLAG_NEED_FILE
INTERNET_FLAG_NO_CACHE_WRITE
- Directory listing is not to be cached.
INTERNET_FLAG_RELOAD
- Forces the directory listing to come from the FTP server rather than using cached information.
INTERNET_FLAG_RESYNCHRONIZE
dwContent
- Application defined value, which is used only if the application has already called
InternetSetStatusCallback
to set up a callback. Otherwise use 0.
Returns: A handle for the search (use with
InternetFindNextFile
to retrieve
the remaining matching files). If the function fails it returns NULL. The
actual error code is returned by a call to GetLastError(), typically
ERROR_NO_MORE_FILES
if there were no matching files.
Note:
- Be aware that only one search can be made within a given FTP session.
Call
InternetCloseHandle
to close the search handle to close the session handle, otherwise future searches will fail withERROR_FTP_TRANSFER_IN_PROGRESS
. - Some of the common information about files, such as file creation date and time is not always available. FtpFindFirstFile and InternetFindNextFile will fill in unavailable information based on what information is available. For this reason creation and last access dates will often be the same as the file modification date.
- To ensure that what is read is current, and not older cached information,
use
INTERNET_FLAG_RELOAD
. - Follow this link
for an example using
FtpFindFirstFile
.
FtpGetCurrentDirectory
Retrieves the current working directory from the server.
function FtpGetCurrentDirectory( hConnect: HINTERNET; lpszCurrentDirectory: PChar; var lpdwCurrentDirectory: DWORD): BOOL;
FtpGetFile
Copies a file from the server to a local directory.
function FtpGetFile( hConnect: HINTERNET; lpszRemoteFile: PChar; lpszNewFile: PChar; fFailIfExists: BOOL; dwFlagsAndAttributes: DWORD; dwFlags: DWORD; dwContext: DWORD): BOOL
Parameters:
- hConnect
- Connection handle for the current FTP session.
- lpszRemoteFile
- The name of the file to be copied down from the server.
- lpszNewFile
- The name of the file after it is copied down. This is normally the same as the remote file name, but does not need to be.
- fFailIfExists
- Flag indicating whether the download should go ahead if a file with the new-file-name already exists. If True and the file exists then the function will fail. If False and the file exists then it will be overwritten.
- dwFlagsAndAttributes
- File attributes to specify for the new downloaded file.
- dwFlags
- Flags affecting the download.
Use on of:
- FTP_TRANSER_TYPE_ASCII
- Copy the file using ASCII transfer.
- FTP_TRANSFER_TYPE_BINARY
- Copy the file as a binary file.
- FTP_TRANSFER_TYPE_UNKNOWN
- Uses FTP_TRANSFER_TYPE_BINARY.
- INTERNET_FLAG_TRANSFER_ASCII
- Uses FTP_TRANSFER_TYPE_ASCII.
- INTERNET_FLAG_TRANSFER_BINARY
- Uses FTP_TRANSFER_TYPE_BINARY.
- and any combination of the following (which affect caching of the file):
- INTERNET_FLAG_HYPERLINK
- Forces a download of the file if the server if the server does not return Expires or LastModified times for the file.
- INTERNET_FLAG_NEED_FILE
- Causes a temporary file to be created even if the file cannot be cached.
- INTERNET_FLAG_RELOAD
- Forces a download of the file from the server, even if it has already been cached.
- INTERNET_FLAG_RESYNCHRONIZE
- If the file has already been cached then it causes a download of the file if the version at the server has been modified more recently than that in the cache.
- dwContext
- Application defined value, which is used only if the application has already called
InternetSetStatusCallback
to set up a callback. Otherwise use 0.
Returns: True if successful, False otherwise. The actual error code is
returned by a call to GetLastError()
.
FtpGetFileSize
Returns the size of a previously opened file from the server.
function FtpGetFileSize( hFile: HINTERNET; lpdwFileSizeHigh: LPDWORD): DWORD;
Parameters:
hFile
- Handle returned from FtpOpenFile.
lpdwFileSizeHigh
- High order unsigned long integer of the file size.
Returns: The low order unsigned long integer of the file size.
FtpOpenFile
Opens a file on the server.
function FtpOpenFile( hConnect: HINTERNET; lpszFileName: PChar; dwAccess: DWORD; dwFlags: DWORD; dwContext: DWORD): HINTERNET;
FtpPutFile
Copies a local file to the server.
function FtpPutFile( hConnect: HINTERNET; lpszLocalFile: PChar; lpszNewRemoteFile: PChar; dwFlags: DWORD; dwContext: DWORD): BOOL;
Parameters:
hConnect
- Connection handle for the current FTP session.
lpszLocalFile
- Pointer to a null-terminated string that contains the name of the local file. This should include the path to the file if the file is not in the current directory.
lpszNewRemoteFile
- Pointer to a null-terminated string that contains the name of the file to create on the remote system.
dwFlags
- Transfer and caching control flags. Specify one of the following transfer flags:
FTP_TRANSFER_TYPE_ASCII
- Copy the file using ASCII transfer. Copying from a Windows system to a Unix system carriage-return-line-feed pairs are replaced by carriage-return, and vice versa when copying to Windows from a Unix system.
FTP_TRANSFER_TYPE_BINARY
- Copy the file as a binary file - file copies exactly as is with no character translation.
FTP_TRANFER_TYPE_UNKNOWN
- Uses
FTP_TRANSFER_TYPE_BINARY
.
INTERNET_FLAG_TRANSFER_ASCII
- Same as
FTP_TRANSFER_TYPE_ASCII
.
INTERNET_FLAG_TRANSFER_BINARY
- Same as
FTP_TRANSFER_TYPE_BINARY
.If required, specify one or more of the following flags (OR them):
INTERNET_FLAG_HYPERLINK
INTERNET_FLAG_NEED_FILE
INTERNET_FLAG_RELOAD
INTERNET_FLAG_RESYNCHRONIZE
dwContext
- Application defined value, which is used only if the application has already called
InternetSetStatusCallback
to set up a callback. Otherwise use 0.
Returns: True if successful, False otherwise. The actual error code is
returned by a call to GetLastError()
.
For example:
if not FtpPutFile(m_hFtpSession,PChar(localFile),
PChar(fileName), FTP_TRANSFER_TYPE_BINARY,0)
then
WriteLn(Format('Failed to copy file %s to %s (error %d).',
[fileName,toDirectory,GetLastError()]));
See also:
FtpRemoveDirectory
Deletes a directory from the server.
function FtpRemoveDirectory( hConnect: HINTERNET; lpszDirectory: PChar): BOOL;
FtpRenameFile
Renames the specified file on the server.
function FtpRenameFile( hConnect: HINTERNET; lpszExisting: PChar; lpszNew: PChar): BOOL;
Returns: True if successful, False otherwise. The actual error code is
returned by a call to GetLastError()
. Additional information
may be found by calling InternetGetLastResponseInfo
.
FtpSetCurrentDirectory
Sets the current working directory on the server.
function FtpSetCurrentDirectory( hConnect: HINTERNET; lpszDirectory: PChar): BOOL;
Returns: True if successful, False otherwise. The actual error code is
returned by a call to GetLastError()
. Additional information
may be found by calling InternetGetLastResponseInfo
.
HttpQueryInfo
Retrieves response header information associated with a HTTP request.
function HttpQueryInfo( hRequest: HINTERNET; dwInfoLevel: DWORD; lpvBuffer: Pointer; var lpdwBufferLength: DWORD; var lpdwIndex: DWORD): BOOL;
Parameters:
hRequest
- Handle returned by
HttpOpenRequest
orInternetOpenUrl
.dwInfoLevel
- Flags indicating what information is required.
HTTP_QUERY_RAW_HEADERS_CRLF
returns all the headers, separated by carriage return line feed combinations.HTTP_QUERY_STATUS_CODE
returns just the status code response. See the WinInet unit for a full list of flags, the flags are named HTTP_QUERY_???.lpvBuffer
- Character buffer to hold the header information.
lpdwBufferLength
- The size of the buffer passed in.
lpdwReserved
- In many versions of Delphi this parameter is
lpdwReserved
, but in later versions islpdwIndex
. It is a zero based index indicating which header to return. Useful where server may result multiple headers.
Returns: True if successful, False otherwise. The actual error code is
returned by a call to GetLastError()
.
Note:
- For an example using HttpQueryInfo see "How to determine if a URL is valid using HttpQueryInfo"
InternetAttemptConnect
Attempts to make a connection to the internet. An application can use this to evoke the dial-up dialog box if there is no internet connection. If the connection attempt fails then the application should enter offline mode.
function InternetAttemptConnect( dwReserved: DWORD): DWORD;
Parameters:
dwReserved
- Reserved parameter. Must be set to 0.
Returns: ERROR_SUCCESS if a connection to the internet has been established. successful, or other error code if unsuccessful.
InternetCloseHandle
Closes an internet handle previously returned/opened by
InternetConnect
or
InternetOpen
.
function InternetCloseHandle(hInet: HINTERNET): BOOL;
InternetConnect
Opens a session for FTP, HTTP or Gopher application.
function InternetConnect( hInet: HINTERNET; lpszServerName: PChar; nServerPort: INTERNET_PORT; lpszUsername: PChar; lpszPassword: PChar; dwService: DWORD; dwFlags: DWORD; dwContext: DWORD): HINTERNET;
Parameters:
hInet
- Valid handle returned by a previous call to InternetOpen.
lpszServerName
- String containing the host name of the server. Alternately this may contain the ip address of the server in text notation.
nServerPort
- Value indicating the TCP/IP port on the server. Use one of:
INTERNET_DEFAULT_FTP_PORT
- Use the default port for FTP servers (port 21).
INTERNET_DEFAULT_GOPHER_PORT
- Use the default port for Gopher servers (port 70).
INTERNET_DEFAULT_HTTP_PORT
- Use the default port for HTTP servers (port 80).
INTERNET_DEFAULT_HTTPS_PORT
- Use the default port for HTTPS servers (port 443).
INTERNET_DEFAULT_SOCKS_PORT
- Use the default port for SOCKS firewall servers (port 1080).
INTERNET_INVALID_PORT_NUMBER
- Use the default port for the type of service specified by dwService.
lpszUsername
- User name to connect with. If NIL then an appropriate default is used, except for HTTP where the function will fail.
lpszPassword
- Password to use. If a username is supplied but the password is nil then the blank password is used. If the username is nil and the password is nil then the default password 'anonymous' is used, except for FTP where the default password is the users's e-mail name.
dwService
- Value indicating the type of service to access. Use one of:
INTERNET_SERVICE_FTP
- FTP service.
INTERNET_SERVICE_GOPHER
- Gopher service.
INTERNET_SERVICE_HTTP
- HTTP service.
dwFlags
- Flags specific to the type of service. Use one of:
INTERNET_FLAG_EXISTING_CONNECT
- Use an existing connection if there is already an identical connection.
INTERNET_FLAG_PASSIVE
- Use passive FTP semantics. Required if server is behind certain firewalls.
WININET_API_FLAG_ASYC
- Allow asynchronous operations.
WININET_API_FLAG_SYNC
- Forces synchronous operations.
dwContent
- Application defined value, which is used only if the application has already called
InternetSetStatusCallback
to set up a callback. Otherwise use 0.
Returns: A valid handle for use with other API calls, or NIL if the call
fails. The actual error code is returned by a call to GetLastError(). A
call to InternetGetLastResponseInfo
may help determine why access to the service was denied.
Note:
- For FTP connections the function establishes a connection immediatly, for all other types the connection is actually established when the application first interacts with the server.
- When the application has finished with the returned handle is should be closed using InternetCloseHandle.
InternetDial
Dials an internet connection using a modem.
function function InternetDial( hwndParent: HWND; lpszConnectoid: LPTSTR; dwFlags: DWORD; lpdwConnection: LPDWORD; dwReserved: DWORD): DWORD;
Parameters:
- hwndParent
- Handle to the parent window. Typically use either '
self.Handle
' or 'application.Handle
'.
- lpszConnectoid
- String containing the name of the dial up connection to use.
- dwFlags
- Dial options, use one or more of the following (or-ed together):
- INTERNET_AUTODIAL_FORCE_ONLINE
- Forces the wininet system online.
- INTERNET_AUTODIAL_FORCE_UNATTENDED
- Use an unattended dial-up. The dial-up will fail if user intervention is required (such as for entering a password).
- INTERNET_DIAL_FORCE_PROMPT
- Forces the dialing interface dialog to be displayed.
- INTERNET_DIAL_UNATTENDED
- If user attention is not required then dial up without displaying the dial-up dialog.
- INTERNET_DIAL_SHOW_OFFLINE
- Display "Work Offline" instead of "Cancel" on the dial-up interface dialog.
- lpdwConnection
- On exit holds a connection number. Use this with InternetHangUp to hang up the connection.
- dwReserved
- Reserved. Must be set to 0.
Returns: ERROR_SUCCESS
if successful, or an error value
which will typically be one of:
ERROR_INVALID_PARAMETER
- One or more of the parameters is incorrect.
ERROR_NO_CONNECTION
- Failed to connected - there is a problem with the dial-up connection.
ERROR_USER_DISCONNECTION
- The user selected either the 'Work Offline' button or the 'Cancel' button from the connection dialog box.
Note:
- If the WinInet subsystem is currently working off-line then this function will return ERROR_SUCCESS, 0 for the connection number and will not dial the connection specified. In this instance to force the dial-up connection, change the state of the WinInet subsystem to online and call the function again.
- The function will also return ERROR_SUCCESS and 0 for the connection number if the connection has already been dialled and is already active.
- If you are missing the definition for INTERNET_DIAL_FORCE_PROMPT then use the following:
const INTERNET_DIAL_FORCE_PRMPT = $2000;
InternetFindNextFile
Used to continue a search started with FtpFindFirstFile.
function InternetFindNextFile( hFind: HINTERNET; lpvFindData: Pointer): BOOL;
Note:
InternetGetConnectedState
Retrieves the connection state of the local system.
function InternetGetConnectedState( var lpdwFlags: DWORD; dwReserved: DWORD): BOOL;
Parameters:
- lpdwFlags
- On exit holds a combination of flags (or-ed together) giving the connection status of the locate system:
INTERNET_CONNECTION_CONFIGURED
- Local system has a valid connection to the Internet, but it might or might not be currently connected.
INTERNET_CONNECTION_LAN
- Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_MODEM
- Local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_OFFLINE
- Local system is in offline mode.
INTERNET_CONNECTION_PROXY
- Local system uses a proxy server to connect to the Internet.
INTERNET_RAS_INSTALLED
- Local system has RAS installed.
- dwReserved
- Not currently used. Must be set to 0.
Returns: True if there is an Internet connection, False otherwise.
InternetGetConnectedStateEx
Retrieves the connection state of the local system.
function InternetGetConnectedStateEx( var lpdwFlags: DWORD; lpszConnectionName: PCHAR; dwNameLen: DWORD; dwReserved: DWORD): BOOL;
Parameters:
- lpdwFlags
- On exit holds a combination of flags (or-ed together) giving the connection status of the locate system:
INTERNET_CONNECTION_CONFIGURED
($40)- Local system has a valid connection to the Internet, but it might or might not be currently connected.
INTERNET_CONNECTION_LAN
($02)- Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_MODEM
($01)- Local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_OFFLINE
($20)- Local system is in offline mode.
INTERNET_CONNECTION_PROXY
($04)- Local system uses a proxy server to connect to the Internet.
INTERNET_RAS_INSTALLED
($10)- Local system has RAS installed.
- lpszConnectionName
- String buffer into which is written the name of the current connection.
- dwNameLen
- Size of the buffer (
lpszConnectionName
) supplied
- dwReserved
- Not currently used. Must be set to 0.
Returns: True if there is an Internet connection, False otherwise.
Note: If the WinInet unit is missing a definition for InternetGetConnectedStateEx
then use the following:
function InternetGetConnectedStateEx(
lpdwFlags: LPDWORD;
lpszConnectionName: LPTSTR;
dwNameLen: DWORD;
dwReserved: DWORD): BOOL; stdcall;
external 'wininet.dll' name 'InternetGetConnectedStateEx';
InternetGetLastResponseInfo
Returns the text of the last WinInet error or server response (for the current thread).
function InternetGetLastResponseInfo( var lpdwError: DWORD; lpszBuffer: PChar; var lpdwBufferLength: DWORD): BOOL;
Parameters:
lpdwError
- Updated to hold the most recent error code.
lpszBuffer
- Buffer to receive the error text.
lpdwBufferLength
- On entry this should be set to the available size of the buffer (lpszBuffer), updated on exit to hold the size of the string written to the buffer (less the null terminator). If the buffer is too small this will hold the necessary buffer size.
Returns: True if some error text was successfully written to the buffer,
False (0) otherwise. If the function fails, further information can be found
by calling GetLastError
. If the buffer is too small to hold
the full error text then GetLastError will return ERROR_INSUFFICIENT_BUFFER
.
Note:
- Use
InternetGetLastResponseInfo
when GetLastError returnsERROR_INTERNET_EXTENDED_ERROR
.
InternetHangUp
Hangs up the modem connection which had previously been opened by InternetDial.
function InternetHangUp( dwConnection: DWORD; dwReserved: DWORD): DWORD;
Parameters:
- dwConnection
- Connection id (as returned by
InternetDial
) indicating the connection to be disconnected.
- dwReserved
- Reserved. Must be 0.
Returns: ERROR_SUCCESS
on success or any other error value
on failure.
Note:
- This function will hang up the modem even if another application is using the connection.
InternetOpen
Initialises the WinInet API.
function InternetOpen( lpszAgent: PChar; dwAccessType: DWORD; lpszProxy: PChar; lpszProxyBypass: PChar; dwFlags: DWORD): HINTERNET;
Parameters:
- lpszAgent
- Name of the calling application (for example '
PChar(Application.Title)
'). This is used as the user agent for HTTP protocol.- dwAccessType
- Access type required, use one of:
INTERNET_OPEN_TYPE_DIRECT
- Resolve all host names locally.
INTERNET_OPEN_TYPE_PRECONFIG
- Retrieve proxy or direct configuration from the registry.
INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY
- Retrieves proxy or direct configuration from the registry and prevents the use of any start-up script.
INTERNET_OPEN_TYPE_PROXY
- Requests passed on to the proxy. If a proxy bypass list is supplied and the name is on that list then
INTERNET_OPEN_TYPE_DIRECT
is used instead.- lpszProxy
- If dwAccessType is set to
INTERNET_OPEN_TYPE_PROXY
then this should be the name of the proxy server(s) to use. WinInet API functions recognise only CERN type proxies (HTTP only) and TIS FTP gateway (FTP only). If Internet Explorer is installed then SOCKS proxy are also supported. For all other values of dwAccessType this should be set to nil.- lpszProxyBypass
- String containing an optional list of host names or IP addresses, which should not be routed through the proxy. If dwAccessType is not
INTERNET_OPEN_TYPE_PROXY
then this parameter is ignored and should be set to nil.- dwFlags
- Various configuration options. Use one or more of:
INTERNET_FLAG_ASYNC
- Makes only asynchronous requests.
INTERNET_FLAG_FROM_CACHE
- All entries are returned from the local cache. Requests will fail if the item is not in the local cache.
INTERNET_FLAG_OFFLINE
- Same as
INTERNET_FLAG_FROM_CACHE
Returns: Handle for use with the other WinInet API functions or nil if the function fails in which case details of the specific error can be found by calling GetLastError().
Note:
InternetOpen
should be the first WinInet API function called by the application.- When the application finishes using the WinInet API it should call
InternetCloseHandle
to free the handle and any associated resources. - Applications may make more than one call to InternetOpen (although only one is required).
InternetOpenUrl
Opens an FTP, Gopher or HTTP resource.
function InternetOpenUrl(hInet: HINTERNET; lpszUrl: PChar; lpszHeaders: PChar; dwHeadersLength: DWORD; dwFlags: DWORD; dwContext: DWORD): HINTERNET; stdcall;
Parameters:
- hInet
- Valid handle returned by a previous call to InternetOpen or InternetConnect.
- lpszUrl
- String containing the URL to read. Only URLs beginning with ftp:, gopher:, http:, or https: are supported.
- lpszHeaders
- String containing the headers to be sent to the HTTP server. (For more information refer to the Microsoft documentation.) May be nil.
- dwHeadersLength
- The length of the headers string. If -1 and lpszHeaders is not nil then the lpszHeaders string is assumed to be null terminated.
- dwFlags
- One or more of:
INTERNET_FLAG_EXISTING_CONNECT
INTERNET_FLAG_HYPERLINK
INTERNET_FLAG_IGNORE_CERT_CN_INVALID
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS
INTERNET_FLAG_KEEP_CONNECTION
INTERNET_FLAG_NEED_FILE
INTERNET_FLAG_NO_AUTH
INTERNET_FLAG_NO_AUTO_REDIRECT
INTERNET_FLAG_NO_CACHE_WRITE
INTERNET_FLAG_NO_COOKIES
INTERNET_FLAG_NO_UI
INTERNET_FLAG_PASSIVE
INTERNET_FLAG_PRAGMA_NOCACHE
INTERNET_FLAG_RAW_DATA
INTERNET_FLAG_RELOAD
INTERNET_FLAG_RESYNCHRONIZE
INTERNET_FLAG_SECURE
- dwContext
- Application defined value, which is used only if the application has already called
InternetSetStatusCallback
to set up a callback. Otherwise use 0.
Returns: If successful a handle to the FTP, Gopher or HTTP URL resource. Nil on failure, in which case use GetLastError and InternetGetLastResponseInfo to determine the cause of failure.
Note:
- When done, the returned handle should freed using InternetCloseHandle.
- Use InternetReadFile to read data (for files) or InternetFindNextFile (for directories).
- For an example of InternetOpenUrl see the examples "How to obtain HTML from the browser cache", "How to determine if a URL is valid using HttpQueryInfo" or "How to download a file using HTTP"
InternetReadFile
Reads and returns data from an open handle.
function InternetReadFile( hFile: HINTERNET; lpBuffer: Pointer; dwNumberOfBytesToRead: DWORD; var lpdwNumberOfBytesRead: DWORD): BOOL; stdcall;
Parameters:
hFile
- Handle returned by FtpCommand, InternetOpenUrl, FtpOpenFile, GopherOpenFile or HttpOpenRequest.
lpBuffer
- Buffer that will receive the data read.
dwNumberOfBytesToRead
- The number of bytes to read (must be equal to or less than the size of the buffer), normally the size of the buffer.
lpdwNumberOfBytesRead
- The number of bytes of data read. This will be 0 if no data was read - either because there is no more data or on error.
Returns: True if successful, False (0) otherwise. If the function fails,
further information can be found by calling GetLastError
.
Note:
- To read all of the data the application should call InternetReadFile until the function returns true and the number of bytes read is 0. This indicates the end of file.
- For an examples of InternetReadFile see the example "How to obtain HTML from the browser cache" or "How to download a file using HTTP"
InternetSetOption
Sets a WinInet configuration option.
InternetSetOption( hInet: HINTERNET; dwOption: Cardinal; lpBuffer: Pointer; dwBufferLength: Cardinal);
Parameters:
- hInet
- Valid handle returned by a previous call to InternetOpen or InternetConnect. For some options this may be nil.
- dwOption
- The desired option to set. This must be one of:
INTERNET_OPTION_CALLBACK
INTERNET_OPTION_CONNECT_TIMEOUT
- Sets the timeout (in milliseconds) used for internet connection requests. Data is a Cardinal value. Use $FFFFFFFF to indicate no timeout.
INTERNET_OPTION_CONNECT_RETRIES
- Sets the number of times WinInet attempts to resolve and connect to a host. WinInet only attempts to connect once to a given IP address, but where a DNS name resolves to multiple IP addresses this option sets the limit on the number of IP addresses considered. The data is a Cardinal value.
INTERNET_OPTION_CONNECT_BACKOFF
INTERNET_OPTION_SEND_TIMEOUT
- Sets the timeout (in milliseconds) used when waiting for a send request to complete. Data is a Cardinal value.
INTERNET_OPTION_RECEIVE_TIMEOUT
- Sets the timeout (in milliseconds) used when waiting for a response to a request. Data is a Cardinal value.
INTERNET_OPTION_DATA_SEND_TIMEOUT
INTERNET_OPTION_DATA_RECEIVE_TIMEOUT
INTERNET_OPTION_HANDLE_TYPE
INTERNET_OPTION_READ_BUFFER_SIZE
INTERNET_OPTION_WRITE_BUFFER_SIZE
INTERNET_OPTION_ASYNC_ID
INTERNET_OPTION_ASYNC_PRIORITY
INTERNET_OPTION_PARENT_HANDLE
INTERNET_OPTION_KEEP_CONNECTION
INTERNET_OPTION_REQUEST_FLAGS
INTERNET_OPTION_EXTENDED_ERROR
INTERNET_OPTION_OFFLINE_MODE
INTERNET_OPTION_CACHE_STREAM_HANDLE
INTERNET_OPTION_USERNAME
INTERNET_OPTION_PASSWORD
INTERNET_OPTION_ASYNC
INTERNET_OPTION_SECURITY_FLAGS
INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT
INTERNET_OPTION_DATAFILE_NAME
INTERNET_OPTION_URL
INTERNET_OPTION_SECURITY_CERTIFICATE
INTERNET_OPTION_SECURITY_KEY_BITNESS
INTERNET_OPTION_REFRESH
INTERNET_OPTION_PROXY
INTERNET_OPTION_SETTINGS_CHANGED
INTERNET_OPTION_VERSION
INTERNET_OPTION_USER_AGENT
INTERNET_OPTION_END_BROWSER_SESSION
INTERNET_OPTION_PROXY_USERNAME
INTERNET_OPTION_PROXY_PASSWORD
INTERNET_OPTION_CONTEXT_VALUE
INTERNET_OPTION_CONNECT_LIMIT
INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT
INTERNET_OPTION_POLICY
INTERNET_OPTION_DISCONNECTED_TIMEOUT
INTERNET_OPTION_CONNECTED_STATE
- Sets the connected state. Use TInternetConnectedInfo for the data.
INTERNET_OPTION_IDLE_STATE
INTERNET_OPTION_OFFLINE_SEMANTICS
INTERNET_OPTION_SECONDARY_CACHE_KEY
INTERNET_OPTION_CALLBACK_FILTER
INTERNET_OPTION_CONNECT_TIME
INTERNET_OPTION_SEND_THROUGHPUT
INTERNET_OPTION_RECEIVE_THROUGHPUT
INTERNET_OPTION_REQUEST_PRIORITY
INTERNET_OPTION_HTTP_VERSION
INTERNET_OPTION_RESET_URLCACHE_SESSION
INTERNET_OPTION_ERROR_MASK
- lpBuffer
- A record containing information applicable to the selected option.
- dwBufferLength
- The length of the record passed as lpBuffer. Use sizeof(...).
Returns: True if successful, False otherwise. If the function fails,
further information can be found by calling GetLastError
.
InternetSetStatusCallback
Sets a callback function used to provide feedback during asynchronous use of the WinInet API.
function InternetSetStatusCallback( hInet: HINTERNET; lpfnInternetCallback: PFNInternetStatusCallback ): PFNInternetStatusCallback;
Parameters:
hInet
- Valid handle returned by a previous call to InternetOpen or InternetConnect.
lpfnInternetCallback
- The callback function to be used, or NIL to unregister the existing callback function. For more information see InternetStatusCallback.
Returns: Reference to the previously defined status callback function or NIL if there was no previously defined callback function.
Note:
- Both synchronous and asynchronous functions can use the callback function to monitor the progress of a WinInet function.
- A callback function is required for asynchronous operation.
- Asynchronous requests will call the callback function with
INTERNET_STATUS_REQUEST_COMPLETE
when a WinInet function completes. - Callback functions can be specified independently for each handle.
- Callback functions can be changed at any time provided there is no request outstanding on the handle.
- If a callback is defined on the handle returned by InternetOpen then the callback will be inherited for all subsequent handles created by InternetConnect.
InternetStatusCallback
There is no WinInet function called InternetStatusCallback - these notes describe the callback function (which an application sets using InternetSetStatusCallback). To define a callback function the application must provide a callback function with the following definition (procedure and parameter names are not significant, although parameter types are):
procedure InternetStatusCallback( hInet: HINTERNET; dwContext: DWORD; dwInternetStatus: DWORD; lpvStatusInformation: Pointer; dwStatusInformationLength: DWORD); stdcall;
Parameters:
hInet
- Handle for the connection on which the callback function has been invoked.
dwContext
- The context value provided by the application when the the WinInet call was made.
dwInternetStatus
- Status value indicating why the callback function is being called. This will be one of:
INTERNET_STATUS_CLOSING_CONNECTION
- Connection to the server is being closed. lpvStatusInformation will be nil.
INTERNET_STATUS_CONNECTING_TO_SERVER
- Connecting to the socket address pointed to by lpvStatusInformation.
INTERNET_STATUS_CONNECTION_CLOSED
- Connection to the server has been closed. lpvStatusInformation will be nil.
INTERNET_STATUS_CTL_RESPONSE_RECEIVED
- Not implemented.
INTERNET_STATUS_DETECTING_PROXY
- Proxy has been detected.
INTERNET_STATUS_HANDLE_CLOSING
- The handle is closing.
INTERNET_STATUS_HANDLE_CREATED
- InternetConnect has created a new handle. lpvStatusInformation will point to a record of type
INTERNET_ASYNC_RESULT
. The new handle is created prior to the connection, so the application could terminate the connection (using InternetCloseHandle) if the connection takes too long.INTERNET_STATUS_INTERMEDIATE_RESPONSE
- Received an intermediate status code message from the server.
INTERNET_STATUS_NAME_RESOLVED
- Successfully resolved the IP address of the name contained in lpvStatusInformation.
INTERNET_STATUS_PREFETCH
- Not implemented.
INTERNET_STATUS_RECEIVING_RESPONSE
- Waiting for response from server. lpvStatusInformation will be nil.
INTERNET_STATUS_REDIRECT
- An HTTP request is redirecting the request. The lpvStatusInformation parameter points to the new URL. Callback will not be made if the original request specified
INTERNET_FLAG_NO_AUTO_REDIRECT
.INTERNET_STATUS_REQUEST_COMPLETE
- Asynchronous operation has completed. lpvStatusInformation will point to a record of type
INTERNET_ASYNC_RESULT
.INTERNET_STATUS_REQUEST_SEND
- Successfully sent request to server. lpvStatusInformation points to a DWORD value containing the number of bytes sent.
INTERNET_STATUS_RESOLVING_NAME
- Attempting to resolve IP address of name indicated by lpvStatusInformation.
INTERNET_STATUS_RESPONSE_RECEIVED
- Received a response from the server. lpvStatusInformation points to a DWORD containing the number of bytes received.
INTERNET_STATUS_SENDING_REQUEST
- Sending a request to the server. lpvStatusInformation will be NIL.
INTERNET_STATUS_STATE_CHANGE
- Moved between a secure (HTTPS) and nonsecure (HTTP) site. lpvStatusInformation points to a DWORD containing one or more of the following flags:
INTERNET_STATE_CONNECTED
- Connected (i.e. not disconnected).
INTERNET_STATE_DISCONNECTED
- Disconnected - no network connection could be established.
INTERNET_STATE_DISCONNECTED_BY_USER
- Disconnected by user request.
INTERNET_STATE_IDLE
- No network requests are being made by WinInet.
INTERNET_STATE_BUSY
- Network requests are being made by WinInet.
INTERNET_STATUS_USER_INPUT_REQUIRED
- The request requires user input for completion.
- lpvStatusInformation
- Pointer to additional information. Possibly NIL.
- dwStatusInformationLength
- Size of the record pointed by by lpvStatusInformation.
Note:
- The callback function may be called in a thread context different from that of the thread which initiated the request.
- Microsoft recommends always notifying the user when a state change from a secure (HTTPS) site to a non-secure (HTTP) site occurs in order to guard against involuntary information disclosure.
- Minimise work done within the callback function - the WinInet thread is essentially blocked until the callback completes.
- The callback function is never called if the originating WinInet function is passed a context of 0.
These notes are believed to be correct for Delphi 6 and Delphi 7, and may apply to other versions as well.
About the author: Brian Cryer is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.