Блог Alexious

Delphi / Дельфи

Пример использования библиотеки libcurl в delphi(загрузка файла/странички с указанного адреса в файл 'temp').
Создайте пустую форму, поместите на нее Memo, два Button'a, EditBox, ProgressBar, и Label. Ниже приведен код модуля. Пример создавался и проверялся на Delphi 7. В папку с проектом поместите libcurl.dll

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;

type

pCURL=^CURL;
CURL=pointer;

TForm1 = class(TForm)
edt1: TEdit;
btn1: TButton;
btn2: TButton;
lbl1: TLabel;
mmo1: TMemo;
pb1: TProgressBar;
procedure btn2Click(Sender: TObject);
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ouf:Tfilestream;

end;

var
Form1: TForm1;

implementation

const curlib = 'libcurl.dll';

function curl_version:pchar; cdecl; external curlib;
function curl_easy_init:pCURL; cdecl; external curlib;
function curl_easy_perform(curl:pCURL):Integer{CURLCode}; cdecl; external curlib;
function curl_easy_setopt(curl:pCURL; option:Integer{CURLoption}):Integer{CURLCode}; varargs; cdecl; external curlib;
procedure curl_easy_cleanup(curl:pCURL); cdecl; external curlib;

{$R *.dfm}

function CuProgress (
UserData:pointer; DownloadTotal, DownloadNow, UploadTotal, UploadNow:Double): LongInt; cdecl;
begin
Form1.pb1.Max:=round(downloadtotal);
Form1.pb1.Position:=round(downloadnow);
Result:=0;
end;

function CuWrite (
IncomingData: pChar; ItemSize, ItemCount:LongWord; UserData:pointer):LongWord; cdecl;
var I:LongInt;
begin
Result:= ( ItemSize * ItemCount );
Form1.ouf.Write(incomingdata^,result);
end;

procedure TForm1.btn2Click(Sender: TObject);
var ccv:Pchar;
begin
ccv:=curl_version;
lbl1.Caption:=ccv;
end;

procedure TForm1.btn1Click(Sender: TObject);
var ch:pCurl;
err:Integer;
begin
ch:=curl_easy_init;
curl_easy_setopt(ch, 10002{CURLOPT_URL}, edt1.text);
curl_easy_setopt(ch, 20011{CURLOPT_WRITEFUNCTION}, @CuWrite);
curl_easy_setopt(ch, 20056{CURLOPT_PROGRESSFUNCTION}, @CuProgress);
curl_easy_setopt(ch, 43{CURLOPT_NOPROGRESS}, 0);
ouf:=TFileStream.Create('temp',fmCreate);
err:=curl_easy_perform(ch);
curl_easy_cleanup(ch);
ouf.Free;
mmo1.Lines.Add('CURL done, return code:'+IntToStr(err));
end; 
END.

 

Nerdbux!