Common HTTP and FTP WinInet APIs

 

This chapter covers most used WinInet APIs with sample code. I don't see any use of Gopher protocol these days, so I will skip that part for now.

WinInet HTTP APIs

Here is WinInet HTTP APIs hierarchy. To use an Http API, you have to go through the heirarchy. 



Before using any HTTP functions, you must be aware of InternetConnect funtion. Here is syntax for InternetConnect.

HINTERNET InternetConnect(IN HINTERNET hInternetSession, IN LPCSTR lpszServerName, IN INTERNET_PORT nServerPort, IN LPCSTR lpszUsername, IN LPCSTR lpszPassword, IN DWORD dwService, IN DWORD dwFlags, IN DWORD dwContext );

Where hInternetSession is handle retured by InternetOpen. Parameter lpszServerName is name of the server (a host name or host IP). The next parameter, nServerPort allows you to specify a port number. Here are default values for this parameter:

nServerPortValue Description
INTERNET_DEFAULT_FTP_PORTUses the default port for FTP server, port 21.
INTERNET_DEFAULT_GOPHER_PORTUses the default port for Gopher server, port 70.
INTERNET_DEFAULT_HTTP_PORTUses the default port for HTTP server, port 80.
INTERNET_DEFAULT_HTTPS_PORTUses the default port for FTP server or HTTPS, port 443.
INTERNET_DEFAULT_SOCKS_PORTUses the default port for Socks firewall servers, port 1080.
INTERNET_INVALID_PORT_NUMBERUses the default port for the service specified by dwService

Parameter lpszUsername and lpszPassword are UserID and passwords. Next parameter, dwService has three values:

dwServiceValue Description
INTERNET_SERVICE_FTPFTP service.
INTERNET_SERVICE_GOPHERGopher service.
INTERNET_SERVICE_HTTPHTTP service.

Here is an example:

HINTERNET hConnection = InternetConnect( hSession, "
www.dotnetheaven.com", INTERNET_DEFAULT_HTTP_POST, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0 );

Here is a list of HTTP APIs:

HTTP APIsDescription
HttpOpenRequest Opens an HTTP request. You need to pass Internet connection as an input parameter to this function.
HTTPQueryInfo Queries information about a request.
InternetErrorDlg Displays predefined dialog for common Internet errors.
HttpAddRequestHeaders Adds HTTP request headers to the HTTP request handle.
HttpSendRequestSends actual request to the server. This request may be GET or POST.

HttpOpenRequest

This is the first HTTP function, which should be called after InternetConnect. To open an HTTP connection, InternetConnect must pass its third parameter value as INTERNET_DEFAULT_HTTP_PORT. This function sends a request to get or retrieve data depends on the method. Here is syntax:

HINTERNET HttpOpenRequest(IN HINTERNET hHttpSession,IN LPCSTR lpszVerb,    IN LPCSTR lpszObjectName,IN LPCSTR lpszVersion,IN LPCSTR lpszReferer,    IN LPCSTR FAR * lpszAcceptTypes,IN DWORD dwFlags,IN DWORD dwContext);

First line of every HTTP request is a combination of three elements: Method, URI, and Protocol Version. Three parameters lpszVerb, lpszObjectName, and lpszVersion of HttpOpenRequest make first line of HTTP request.

Parameters Description
hHttpSession Handle to the HTTP session returned by InternetConnect.
lpszVerb Address of string containing HTTP method. If you pass NULL, default method is GET.
lpszObjectName URI
lpszVersion Protocol version. If you pass NULL, default is HTTP/1.0.
lpszReferer 
lpszAcceptTypes 
dwFlags 
dwContext HTTP service.

Here is how to use this function:

HINTERNET hRequest = HttpOpenRequest( hConnection, "GET", "", NULL, NULL, INTERNET_FLAG_RELOAD, 0  );

We will see all the APIs in out example. For more details, you can see MSDN.

HttpSendRequest

Another important HTTP function is HttpSendRequest. This function actually sends a request to Http server. This request may be to post or to get data from the server. It depends on the HttpOpenRequest handle.

Syntax:

BOOL HttpSendRequest( IN HINTERNET hHttpRequest, IN LPCSTR lpszHeaders,    IN DWORD dwHeadersLength, IN LPVOID lpOptional, DWORD dwOptionalLength);

Parameters Description
hHttpRequest Handle of HttpOpenReqest
lpszHeaders NULL
dwHeaderLength 0
lpOptional NULL
dwOptionLength 0

Here is how to use this function:

HttpSendRequest( hData, NULL, 0, NULL, 0);

Example: Now let's see how to use all these functions in our example. This example shows how to download contents of a page using HTTP API functions.

HINTERNET hINet, hConnection, hData;
CHAR buffer[2048] ;
CString m_strContents ;
DWORD dwRead, dwFlags, dwStatus ;
hINet = InternetOpen("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
if ( !hINet )
{
AfxMessageBox("InternetOpen Failed");
return;
}
try
{
hConnection = InternetConnect( hINet, "
www.dotnetheaven.com", 80, " "," ", INTERNET_SERVICE_HTTP, 0, 0 );
if ( !hConnection )
{
InternetCloseHandle(hINet);
return;
}
// Get datahData = HttpOpenRequest( hConnection, "GET", "/uicsa/index.htm", NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0 );
if ( !hData )
{
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
return;
}
HttpSendRequest( hData, NULL, 0, NULL, 0);
while( InternetReadFile( hData, buffer, 255, &dwRead ) )
{
if ( dwRead == 0 )
return;
buffer[dwRead] = 0;
m_strContents += buffer;
}
}
catch( CInternetException* e)
{
e->ReportError();
e->Delete();
}
InternetCloseHandle(hConnection);InternetCloseHandle(hINet);
InternetCloseHandle(hData);

HttpAddRequestHeaders

You can add, replace or remove headers to your HTTP request by using this function. Add, replace, or remove depends on dwModifiers parameter. Ok, here is the syntax:

BOOL HttpAddRequestHeaders( IN HINTERNET hHttpRequest, IN LPCSTR lpszHeaders,    IN DWORD dwHeadersLength,  IN DWORD dwModifiers);

Parameters Description
hHttpRequest Handle of http request.
lpszHeaders Header you want to add.
dwHeadersLengthLength of the header.
dwModifierswhat kind of request is it? Add, replace or remove.

Ok, here is an example:

char* chHead = "Accept: image/*/r/n" ; HttpAddRequestHeaders( hHttpHandle, chHead, -1, HTTP_ADDREQ_FLAG_ADD);

HttpQueryInfo

This function allows you to retrieve information about a give HTTP request. Here is the syntax:

BOOL HttpQueryInfo(IN HINTERNET hHttpRequest, IN DWORD dwInfoLevel,    IN LPVOID lpvBuffer,  IN LPDWORD lpdwBufferLength,IN OUT LPDWORD lpdwIndex);

ParametersDescription
hHttpRequest Handle of http request.
dwInfoLevelType of information you are interested in.
lpvBufferBuffer.
lpdwBufferLengthBuffer size
lpdwIndexIndex

Ok, here is an example:

CHAR chBuff[1024];DWORD dwLen 1024;BOOL bRet;bRet = HttpQueryInfo( hRequest, HTTP_QUERY_CUSTOM, chBuff, &dwLen, NULL);
 
WinInet FTP APIs

Here is a list of ftp functions. All FTP functions are easy to understand and use. There is nothing to explain. I have sample examples for most of the functions.

Function Description
FtpCreateDirectory Creates a new directory.
FtpDeleteFileDeletes a file.
FtpFindFirstFileSearches the specified directory of the given FTP session. File and directory entries are returned to the application in the WIN32_FIND_DATA structure.
FtpGetCurrentDirectory Retrieves the current directory for the specified FTP session.
FtpGetFileRetrieves a file from the FTP server and stores it under the specified file name, creating a new local file in the process.
FtpGetFileSizeRetrieves the file size of the requested FTP resource.
FtpOpenFileInitiates access to a remote file on an FTP server for reading or writing.
FtpPutFileStores a file on the FTP server.
FtpRemoveDirectoryRemoves the specified directory.
FtpRenameFileRenames a file.
FtpSetCurrentDirectoryChanges to a different working directory.

FtpCreateDirectory

This function creates a directory on the FTP server.

Syntax:

BOOL FtpCreateDirectory(IN HINTERNET hConnect, IN LPCTSTR lpszDirectory );

Sample:

if (!FtpCreateDirectory(g_hConnection, "NewDir"))
DoSomething();

FtpDeleteFile

This function deletes a file from the FTP server. Nothing to explain here :). Here is the syntax:

BOOL FtpDeleteFile( IN HINTERNET hConnect, IN LPCTSTR lpszFileName);

Sample:

if (!FtpDeleteFile(g_hConnection, strFileName))
DoSomething();

FtpFindFirstFile

This function finds a file on the FTP server and help InternetFindNextFile to find files on the server.

Syntax:

HINTERNET FtpFindFirstFile(IN HINTERNET hConnect,IN LPCTSTR lpszSearchFile,    OUT LPWIN32_FIND_DATA lpFindFileData, IN DWORD dwFlags, IN DWORD_PTR dwContext );

Sample:

CString strFileName = "mcb.asp";
WIN32_FIND_DATA FindFileData;
HINTERNET hFindFile=NULL;
m_RemoteList.ResetContent();
if (hFindFile)
InternetCloseHandle(hFindFile);
hFindFile = FtpFindFirstFile(g_hConnection, szFileName, &FindFileData, INTERNET_FLAG_RELOAD, 0);
if (hFindFile)
{
if ( (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
strFileName.Format("%s <DIR>", FindFileData.cFileName);
else
strFileName = FindFileData.cFileName;
m_RemoteList.AddString(strFileName);
while(InternetFindNextFile(hFindFile, &FindFileData))
{
if ( (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
strFileName.Format("%s <DIR>", FindFileData.cFileName);
else
strFileName = FindFileData.cFileName;
m_RemoteList.AddString(strFileName);
}
InternetCloseHandle(hFindFile);
}

FtpGetCurrentDirectory

This function returns the current active directory of the FTP server. All FTP function applies to current active directory. So this function is plays an important role.

Syntax:

BOOL FtpGetCurrentDirectory(IN HINTERNET hConnect,OUT LPTSTR lpszCurrentDirectory,    IN OUT LPDWORD lpdwCurrentDirectory);

Sample:

char szDir[255];
DWORD dwLen = 255;
//get the current remote directory
if (!FtpGetCurrentDirectory(g_hConnection, szDir, &dwLen))
DoSomething();

FtpGetFile

This function retrieves a file from the FTP server and stores on the local system. Here is the syntax:

BOOL FtpGetFile(IN HINTERNET hConnect, IN LPCTSTR lpszRemoteFile, IN LPCTSTR                lpszNewFile, IN BOOL fFailIfExists,IN DWORD dwFlagsAndAttributes,IN DWORD dwFlags,IN DWORD_PTR dwContext);
 
FtpGetFileSize

Retrieves the file size of the requested FTP resource.

Syntax:

DWORD FtpGetFileSize(IN HINTERNET hFile, OUT LPDWORD lpdwFileSizeHigh);
 
FtpOpenFile

Initiates access to a remote file on an FTP server for reading or writing.

Syntax:

HINTERNET FtpOpenFile (IN HINTERNET hConnect,IN LPCTSTR lpszFileName,IN DWORD dwAccess, IN DWORD dwFlags,IN DWORD_PTR dwContext);

FtpPutFile

Send a local file on the FTP server.

Syntax:

BOOL FtpPutFile(IN HINTERNET hConnect,IN LPCTSTR lpszLocalFile,IN LPCTSTR lpszNewRemoteFile, IN DWORD dwFlags,IN DWORD_PTR dwContext);
DWORD dwFlags;
if (m_lMode == MODE_ASCII) 
dwFlags = FTP_TRANSFER_TYPE_ASCII;
else  
dwFlags = FTP_TRANSFER_TYPE_BINARY;
BOOL bRet = FtpPutFile(g_hConnection, szLocalFile, szRemoteFile, dwFlags, 0);

FtpRemoveDirectory

Removes the specified directory on the FTP server.

Syntax:

BOOL FtpRemoveDirectory(IN HINTERNET hConnect,IN LPCTSTR lpszDirectory)
 
FtpRenameFile

Renames a file stored on the FTP server.

Syntax:

BOOL FtpRenameFile(IN HINTERNET hConnect,IN LPCTSTR lpszExisting,IN LPCTSTR lpszNew);

FtpSetCurrentDirectory Function

Change to a different working directory on the FTP server.

Syntax:

BOOL FtpSetCurrentDirectory(IN HINTERNET hConnect,IN LPCTSTR lpszDirectory);

Other chapters of this tutorial

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值