Le transfert de fichiers sur Internet se fait par le biais des protocoles HTTP
et FTP. Avec l'API Win32 WinInet, il est possible de rappatrier des données
demandées sous la forme d'une URL. Ainsi on peut obtenir n'importe quel objet
que l'on transfert dans un buffer du moment que l'URL soit préfixée de HTPP ou
FTP. Voici la définition des fonctions InternetOpenUrl et InternetReadFile:
HINTERNET InternetOpenUrl(
HINTERNET hInternet,
LPCTSTR lpszUrl,
LPCTSTR lpszHeaders,
DWORD dwHeadersLength,
DWORD dwFlags,
DWORD_PTR dwContext
);
BOOL InternetReadFile(
HINTERNET hFile,
LPVOID lpBuffer,
DWORD dwNumberOfBytesToRead,
LPDWORD lpdwNumberOfBytesRead
);
La fonction InternetOpenUrl passe directement l'URL fourni au serveur
comme lorsque l'on tape une URL sur dans la barre d'adresse du navigateur. La
Fonction InternetReadFile se charge de récupérer le flux de données. Dans
l'application fournie en exemple, le flux de données est immédiatement écrit
dans le fichier DATA.BIN. Dans le cas d'une URL pointant sur un fichier,
DATA.BIN est le fichier téléchargé, mais dans les autres cas on peut se
retrouver avec une page HTML du type:
<html><head><title>Error 404</title>
<meta name="robots" content="noindex">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"></head>
<body>
<h2>HTTP Error 404</h2>
<p><strong>404 Not Found</strong></p>
<p>The Web server cannot find the file or script you asked for. Please check the URL to ensure that the path is correct.</p>
<p>Please contact the server's administrator if this problem persists.</p>
</body></html>
#include "stdafx.h"
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
#pragma comment(lib, "wininet.lib")
void main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Usage: InternetGet server object\n");
return;
}
HINTERNET hSession = InternetOpen("Microsoft Internet Explorer", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET hInternetFile = InternetOpenUrl(hSession,argv[2], NULL, 0,INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, 0);
if (hInternetFile == NULL)
{
printf("InternetOpenUrl failed\n");
return;
}
HANDLE f = CreateFile("DATA.BIN", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL, NULL);
if (f == INVALID_HANDLE_VALUE)
{
printf("CreateFile failed\n");
return;
}
DWORD dwRead = 0;
DWORD dwWritten = 0;
CHAR szTemp[1024];
while (InternetReadFile(hInternetFile, (LPVOID)szTemp, 1024, &dwRead))
{
if (!dwRead) break;
WriteFile(f, (LPVOID)szTemp, dwRead, &dwWritten, NULL);
}
CloseHandle(f);
InternetCloseHandle(hInternetFile);
InternetCloseHandle(hSession);
}
© 2001 Christophe Pichaud. All rights reserved.