Einzelnen Beitrag anzeigen

Benutzerbild von Dani
Dani

Registriert seit: 19. Jan 2003
732 Beiträge
 
Turbo Delphi für Win32
 
#5

Re: Datei Download mit SaveDialog

  Alt 3. Feb 2008, 06:11
Der Webserver könnte will evtl. den Referer oder einen UserAgent verlangen, außerdem solltest du Weiterleitungen behandeln... geht dieser Code?

Delphi-Quellcode:
function DownloadWithDialog(URL: String; SaveDialog: TSaveDialog): Boolean;
const
  UserAgentString: String = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en;' +
                            ' rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11';
  OkResponses: array[0..2] of Integer = (200, 301, 302);
  MinUrlLength: Integer = 8;
  RedirectMaximum: Integer = 5;
var
  HTTP: TIdHttp;
  Stream: TStream;
  I, Slashpos: Integer;
  ForgedReferer: String;
begin
  Result := false;
  if Length(URL) < MinUrlLength then Exit;

  if SaveDialog.Execute then begin
    Stream := TFileStream.Create(SaveDialog.FileName,
                                 fmCreate or fmShareDenyWrite);
    try
      HTTP := TIdHTTP.Create;
      try
        Slashpos := pos('/', copy(URL, MinUrlLength, MaxInt));
        if Slashpos > 0 then begin
          ForgedReferer := copy(URL, 1, MinUrlLength + Slashpos - 1);
        end else begin
          ForgedReferer := URL;
        end;

        HTTP.Request.Referer := ForgedReferer;
        HTTP.Request.UserAgent := UserAgentString;
        HTTP.HandleRedirects := true;
        HTTP.RedirectMaximum := RedirectMaximum;
        try
          HTTP.Get(URL, Stream);
          for I := Low(OkResponses) to High(OkResponses) do begin
            if HTTP.Response.ResponseCode = OkResponses[I] then begin
              Result := true;
              break;
            end;
          end;
        except
          on E: EIdException do begin
            Result := false;
          end;
        end;
      finally
        HTTP.Free;
      end;
    finally
      Stream.Free;
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
const URL = 'http://www.delphipraxis.net/forum22.html';
begin
 if DownloadWithDialog(URL, SaveDialog1) then begin
   ShowMessage('Yay.');
 end else begin
   ShowMessage('Fail.');
 end;
end;
Dani H.
At Least I Can Say I Tried
  Mit Zitat antworten Zitat