1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| procedure TZooShaiVCLMainForm.btnDownloadURLClick(Sender: TObject);
const
BufferSize = 1024;
accept: packed array[0..1] of LPWSTR = (PChar('text/*'), nil); // PCTSTR rgpszAcceptTypes[] = {_T(text/*), NULL};
var
ServerName, URL, Params, LocalFileName: string;
hSession, hHTTP, hReq : HINTERNET;
Buffer: array[1..BufferSize] of Byte;
BufferLen: DWORD;
sAppName: string;
FS: TFileStream;
Headers: string;
Data: RawByteString;
begin
sAppName := ExtractFileName(Application.ExeName);
hSession := InternetOpen(PChar(sAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
if not InputQuery('Download URL', 'Server Name', ServerName) then
Exit;
hHTTP := InternetConnect(hSession, PChar(ServerName), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
try
if not InputQuery('Download URL', 'URL', URL) then
Exit;
hReq := HttpOpenRequest(hHTTP, PChar('POST'), PChar(URL), nil, nil, @accept, 0, 1);
try
Headers := 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
if not InputQuery('Download URL', 'Params', Params) then
Exit;
Data := UTF8Encode(Params);
if HttpSendRequest(hReq, PChar(Headers), length(Headers), PAnsiChar(Data), length(Data)) then
begin
LocalFileName := StringReplace(URL, '/', '_', [rfReplaceAll]);
if not PromptForFileName(LocalFileName, '', '.txt', 'Download URL into Local File', '', True) then
Exit;
FS := TFileStream.Create(LocalFileName, fmCreate);
try
BufferLen := 0;
repeat
if InternetReadFile(hReq, @Buffer, BufferSize, BufferLen) then
FS.WriteBuffer(Buffer, BufferLen);
until BufferLen = 0;
finally
FS.Free;
end;
end
else
raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
finally
InternetCloseHandle(hReq);
end;
finally
InternetCloseHandle(hHTTP);
end;
finally
InternetCloseHandle(hSession);
end;
end; |
Partager