Reputation: 167
I need to program an application with Delphi that goes into this site and uses the form to get an .exe file (in fact, the site sends a .ex_ file that you have to manually rename).
http://www.bmf.com.br/arquivos1/arquivos_ipn.asp?idioma=pt-BR&status=ativo
Via browser I just click on the checkbox on the left of "Cenários de Margem - CORE" then click on the Download button and get the file automatically.
I managed to work with .dat files from other site, now I don't know what might be wrong.
I think the problem should be with the content type or how i'm saving the file.
This is what I got so far:
procedure DownloadViaPost;
var
objHttp: TIdHttp;
sUrl: String;
sGetRequest: String;
objParametrosPost: TStringList;
objRespostaPost: TStringStream;
sViewState: String;
sEventValidation: String;
begin
sUrl := 'http://www.bmf.com.br/arquivos1/arquivos_ipn.asp';
objHttp := TIdHTTP.Create(nil);
objParametrosPost := TStringList.Create;
objRespostaPost := TStringStream.Create;
try
objHttp.HandleRedirects := true;
objHttp.AllowCookies := true;
objParametrosPost.Add('hdnStatus=ativo');
objParametrosPost.Add('chkArquivoDownload_ativo=36');
objParametrosPost.Add('txtDataDownload_ativo=21/08/2014');
objParametrosPost.Add('imgSubmeter.x=31');
objParametrosPost.Add('imgSubmeter.y=9');
objParametrosPost.Add('imgSubmeter=ativo');
objHttp.Request.ContentType := 'application/octet-stream exe';
objHttp.Post(sUrl, objParametrosPost, objRespostaPost);
objRespostaPost.SaveToFile('C:\Download.ex_');
finally
FreeAndNil(objHttp);
FreeAndNil(objParametrosPost);
FreeAndNil(objRespostaPost);
end;
end;
Upvotes: 1
Views: 446
Reputation: 598279
Just like a browser would, you need to first retreive the download page to get the server's cookies, then post the download request so the cookies can be sent back to the server.
Try this:
procedure DownloadViaPost;
var
objHttp: TIdHttp;
objRespostaPost: TMemoryStream;
objParametrosPost: TStringList;
begin
objHttp := TIdHTTP.Create(nil);
try
objHttp.HandleRedirects := true;
objHttp.AllowCookies := true;
objHttp.Get('http://www.bmf.com.br/arquivos1/arquivos_ipn.asp?idioma=pt-BR&status=ativo');
objRespostaPost := TMemoryStream.Create;
try
objParametrosPost := TStringList.Create;
try
objParametrosPost.Add('hdnStatus=ativo');
objParametrosPost.Add('chkArquivoDownload_ativo=36');
objParametrosPost.Add('txtDataDownload_ativo=22/08/2014');
objParametrosPost.Add('imgSubmeter.x=37');
objParametrosPost.Add('imgSubmeter.y=6');
objHttp.Request.Referer := 'http://www.bmf.com.br/arquivos1/arquivos_ipn.asp?idioma=pt-BR&status=ativo';
objHttp.HTTPOptions := objHttp.HTTPOptions + [hoKeepOrigProtocol, hoTreat302Like303];
objHttp.Post('http://www.bmf.com.br/arquivos1/download_ipn.asp', objParametrosPost, objRespostaPost);
finally
FreeAndNil(objParametrosPost);
end;
objRespostaPost.SaveToFile('C:\Download.exe');
finally
FreeAndNil(objRespostaPost);
end;
finally
FreeAndNil(objHttp);
end;
end;
Upvotes: 3