怎样下载指定URL的文件?(50分)

  • 主题发起人 主题发起人 Nstar
  • 开始时间 开始时间
当然就是http协议就可以了,利用clientSocket就可以了
 
能举个简单的例子吗?
 
你用打开这个Socket,然后发送一个http包,这个包包含你的信息,然后,就接收信息,直接等到Disconnet,将所有接收的信息保存起来就可以了,注意,接收的第一个包里面有头信息
 
uses Wininet;
function GetInetFile (const fileURL, FileName: String): boolean;
const BufferSize = 1024;
var
hSession, hURL: HInternet;
Buffer: array[1..BufferSize] of Byte;
BufferLen: DWORD; f: File;
sAppName: string;
begin
Result:=False;
sAppName := ExtractFileName(Application.ExeName);
hSession := InternetOpen(PChar(sAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
hURL := InternetOpenURL(hSession, PChar(fileURL), nil,0,0,0);
try
AssignFile(f, FileName); Rewrite(f,1);
repeat
InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
BlockWrite(f, Buffer, BufferLen)
until BufferLen = 0;
CloseFile(f);
Result:=True;
finally
InternetCloseHandle(hURL)
end
finally
InternetCloseHandle(hSession)
end
end;

用法:
var
FileOnNet, LocalFileName: string
begin
FileOnNet:= 'http://www.your.com/file.zip';
LocalFileName:='netfile.zip';
if GetInetFile(FileOnNet,LocalFileName)=True then
ShowMessage('下载成功!')
else
ShowMessage('下载失败!')
end;
 
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, StdCtrls, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP;

type
TForm1 = class(TForm)
IdHTTP1: TIdHTTP;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
aStream : TStream ;
aMm: TMemoryStream;
begin
aStream := TMemoryStream.Create;
aMm := TMemoryStream.Create;
try
IdHTTP1.Get('http://www.delphibbs.com/delphibbs/dispq.asp?lid=1965233',aStream);
aStream.Seek(0, soFromBeginning);
aMm.Seek(0, soFromBeginning);
aMm.CopyFrom(aStream,aStream.Size);
aMm.SaveToFile('c:/test.txt');
finally
aMm.Free;
aStream.Free;
end;
end;

end.
 
后退
顶部