Blue Theme Orange Theme Green Theme Red Theme
 
Safari Books Online
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Safari Books Online
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Tutorials » Common HTTP and FTP WinInet APIs

Common HTTP and FTP WinInet APIs


This article explains about the HTTP and FTP Protocols and some of their common functions.This article also explains about the WinInet and the Gopher Protocols.

Author Rank:
Total page views :  61157
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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:

nServerPort Value Description
INTERNET_DEFAULT_FTP_PORT Uses the default port for FTP server, port 21.
INTERNET_DEFAULT_GOPHER_PORT Uses the default port for Gopher server, port 70.
INTERNET_DEFAULT_HTTP_PORT Uses the default port for HTTP server, port 80.
INTERNET_DEFAULT_HTTPS_PORT Uses the default port for FTP server or HTTPS, port 443.
INTERNET_DEFAULT_SOCKS_PORT Uses the default port for Socks firewall servers, port 1080.
INTERNET_INVALID_PORT_NUMBER Uses the default port for the service specified by dwService

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

dwService Value Description
INTERNET_SERVICE_FTP FTP service.
INTERNET_SERVICE_GOPHER Gopher service.
INTERNET_SERVICE_HTTP HTTP 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 APIs Description
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.
HttpSendRequest Sends 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.
dwHeadersLength Length of the header.
dwModifiers what 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);

Parameters Description
hHttpRequest  Handle of http request.
dwInfoLevel Type of information you are interested in.
lpvBuffer Buffer.
lpdwBufferLength Buffer size
lpdwIndex Index

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.
FtpDeleteFile Deletes a file.
FtpFindFirstFile Searches 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.
FtpGetFile Retrieves a file from the FTP server and stores it under the specified file name, creating a new local file in the process.
FtpGetFileSize Retrieves the file size of the requested FTP resource.
FtpOpenFile Initiates access to a remote file on an FTP server for reading or writing.
FtpPutFile Stores a file on the FTP server.
FtpRemoveDirectory Removes the specified directory.
FtpRenameFile Renames a file.
FtpSetCurrentDirectory Changes 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


Login to add your contents and source code to this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
 Comments
HttpSendRequest's Speed by Anthony On January 23, 2009
Hi, I am Anthony from Singapore. First, thank you for this excellent article. It really helped me to use WinInet. I have a question regarding the speed of HttpSendRequest. I am developing a real-time application. I found that HttpSendRequest is quite slow in processing. I used following code to find the processing time: clock_t start_time = clock(); HttpSendRequest( hData, Iheader, lstrlen( Iheader ), cgiParam, strlen( cgiParam ) ); cout << "time: " << ( ( clock() - start_time ) / CLOCKS_PER_SEC ) << endl; It turned out the processing time was always more than 1 second (usually 2 second and more). Do you have any suggestion to improve the processing time? Thank you.
Reply | Email | Delete | Modify | 
Re: HttpSendRequest's Speed by Mahesh On April 6, 2009
I haven't worked on C++ in last 9 years. Pls post your question on C# Corner forums.

Best,
Mahesh
Reply | Email | Delete | Modify | 
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.