Zum Hauptinhalt springen

Beispiel - Datei herunterladen (HTTP)

Beispiel - Datei herunterladen (über HTTP-Objekt) Einfache Kommunikation über HTTP zum Download einer Datei

In diesem Beispiel wird mit Hilfe des HTTP -Objekts eine Datei von einem HTTP-Server heruntergeladen und lokal gespeichert. Beim Aufruf der Funktion muss die URI und der Pfad und Dateiname angegeben werden.

sub DownloadFile
(
aURI : alpha(512);
aDestFile : alpha;
)
: int;

local
{
tHost : alpha(128); // Hostname
tPath : alpha(512); // Path
tPos : int;
tError : int; // Errorcode

tSck : handle; // Socket
tReq : handle; // Request-Object
tRsp : handle; // Response-Object
tLst : handle; // HTTP-Header-List
tFsi : handle; // File
}

{
if (!(aURI =* 'http://*'))
return(_ErrData);

// URI in Host und Pfad zerlegen
tPos # StrFind(aURI, '/', 8);
if (tPos = 0)
{
tHost # StrCut(aURI, 8, StrLen(aURI) - 7);
tPath # '/';
}
else
{
tHost # StrCut(aURI, 8, tPos - 8);
tPath # StrCut(aURI, tPos, StrLen(aURI) + 1 - tPos);
}

try
{
// Verbindung aufbauen
tSck # SckConnect(tHost, 80, 0, 10000);

// Anfrage erzeugen
tReq # HttpOpen(_HttpSendRequest, tSck);
tLst # tReq->spHttpHeader;
tReq->spURI # tPath;
tReq->spProtocol # 'HTTP/1.1';
tLst->CteInsertItem('Host', 0, tHost);
tLst->CteInsertItem('Accept', 0, '*/*');

// Anfrage senden
tReq->HttpClose(_HttpCloseConnection);
tReq # 0;

// Antwort abholen
tRsp # HttpOpen(_HttpRecvResponse, tSck);
if (tRsp->spStatusCode =* '200*' and
tRsp->spContentLength > 0)
{
tFsi # FsiOpen(aDestFile, _FsiStdWrite);
// Datei speichern
tRsp->HttpGetData(tFsi);
}
}

tError # ErrGet();

// angelegte Deskriptoren entfernen
if (tReq > 0)
tReq->HttpClose(_HttpDiscard);
if (tFsi > 0)
tFsi->FsiClose();
if (tRsp > 0)
tRsp->HttpClose(0);
if (tSck > 0)
tSck->SckClose();

return(tError);
}